23.5 C
New York
Thursday, September 26, 2024

Buy now

The Full Information to Getting Began with the NetSuite API


Oracle NetSuite provides a robust API for integrating and lengthening your enterprise workflows, however working successfully with these APIs requires a strong understanding of how they perform.

On this information we dive deep into the evolution of NetSuite’s API choices, the variations between NetSuite’s SOAP and REST APIs, establishing API-based functions, and scaling your deployments – all whereas leveraging NetSuite’s SuiteQL and SuiteScript for extra complicated eventualities. We’ll additionally discover how instruments like Nanonets may help automate your workflows throughout information layers.


Understanding NetSuite’s API Ecosystem

NetSuite began with the SuiteTalk SOAP API 20 years in the past, and it grew to become the go-to answer for companies trying to combine their programs with NetSuite’s deep characteristic set. For a few years, this was the usual API for NetSuite improvement.

To handle the eventual limitations within the SOAP API, NetSuite launched its REST API in 2019, providing an easier, extra scalable strategy to entry information. The REST API embraced trendy internet requirements like JSON, offering simpler integration with cloud-native functions and APIs. Nevertheless, not all is nice with the REST API, as we are going to see later on this information.

NetSuite additionally launched SuiteQL, launched alongside the REST API – to additional enhance information querying with SQL-like syntax. Because it seems, SuiteQL some of the helpful options of the REST API.

The SuiteTalk SOAP API

The NetSuite SOAP API has remained the usual for a few years for any NetSuite integrations, and even as we speak loads of integrations will utilise the SOAP API just because it’s dependable and has good help.

The API makes use of complicated XML payloads and has strict formatting, so whereas it would initially appear good to have a excessive degree of element in each API name, it may well shortly change into cumbersome for circumstances the place you might want to combine the APIs at some degree of scale.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/cleaning soap/envelope/" xmlns:platform="urn:platform_2013_2.webservices.netsuite.com">
  <soapenv:Header>
    <platform:tokenPassport>
      <platform:account>123456</platform:account>
      <platform:consumerKey>abc123</platform:consumerKey>
      <platform:token>def456</platform:token>
      <platform:nonce>random123</platform:nonce>
      <platform:timestamp>1627891230</platform:timestamp>
    </platform:tokenPassport>
  </soapenv:Header>
  <soapenv:Physique>
    <platform:recordRef internalId="12345" sort="purchaseOrder"/>
  </soapenv:Physique>
</soapenv:Envelope>

NetSuite SOAP API payloads will not be all the time developer-friendly.

Additional, the entire metadata (principally the information about the NetSuite objects) is saved in a format referred to as WSDL (Internet Companies Description Language). And the one metadata you get is that of the customary NetSuite modules, objects and fields.

So when you created any customized fields (or, god forbid, whole customized objects) – you will not see them right here. There is a good method round this – utilizing RESTlets – however that may shortly get messy.

What are RESTlets? Earlier than we go additional, let’s perceive a couple of NetSuite API ideas (be at liberty to skip forward if you’re already properly versed).

SuiteScript and RESTlets

To outline a RESTlet, we’ll first should outline what SuiteScript is.

💡

SuiteScript is a scripting language based mostly on JavaScript, that enables NetSuite builders (sure, that is you) to create custom-made scripts and capabilities that may be triggered on sure actions/occasions. It is a nifty strategy to customise non-standard actions in NetSuite.

This is a pattern SuiteScript that updates the e-mail tackle of a buyer report in NetSuite:

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 */
outline(['N/record'], perform(report) {
    perform beforeSubmit(context) {
        var customerRecord = context.newRecord;
        
        // Set a brand new electronic mail tackle
        customerRecord.setValue({
            fieldId: 'electronic mail',
            worth: '[email protected]'
        });
    }
    
    return {
        beforeSubmit: beforeSubmit
    };
});

💡

A RESTlet is a SuiteScript that may be executed by one other software exterior NetSuite (or additionally by one other SuiteScript) – and can even return information again to that software.

For instance – you possibly can create a RESTlet to return information from NetSuite on the present stock held. You may then use this information in one other software (like working an approval course of for Buying Managers to approve a purchase order requisition based mostly on present stock ranges).

Nevertheless, creating and scaling RESTlet utilization is cumbersome. It may be achieved, however wants a devoted place to host your code and enterprise logic + hold observe of all customized entities (extra on this later).

The NetSuite REST API

Designed to be light-weight and extra fitted to cloud-based apps, the REST API makes use of JSON payloads, decreasing overhead in information transmission. The transition from SOAP to REST mirrored the rising demand for easier, quicker, and extra accessible integrations, significantly for cell apps and cloud ecosystems.

As is the case with most REST APIs, it may be tempting to fully sideline NetSuite’s SOAP API – just because creating with a REST API is mostly a lot simpler. However in NetSuite’s case, this is not all the time true.

The thing construction within the REST API is troublesome to cope with (owing partly to poor implementation of an object construction referred to as HATEOAS) which principally implies that the information of an object isn’t returned completely in a single go, however in nested hyperlinks.

This is an instance – when you name a REST API endpoint like /distributors you’d usually count on one thing like this within the response:

{
    {
      "vendorId": "123abc",
      "vendorName": "Take a look at Vendor"
    },
    {
      "vendorId": "123abcd",
      "vendorName": "Take a look at Vendor 2"
    },
    {
      "vendorId": "123abcde",
      "vendorName": "Take a look at Vendor 3"
    } 
}

As a substitute, what you get is a set of IDs of every vendor, and API hyperlinks to the person vendor entities themselves. So now you might want to know the ID of the seller you actually wish to get information for.

Should you do not already know this ID, you are going to should iterate over 500+ distributors for any primary operation. Each. Single. Time.

There’s a method out, although, and that’s to make use of SuiteQL.

What’s SuiteQL?

💡

SuiteQL is a question language (like SQL) that permits you to question your entire NetSuite information construction. It is part of the NetSuite REST API, and a useful one at that.

In reality, there may be a whole separate endpoint within the REST API to name SuiteQL. Let’s take the instance above – this is how you should utilize SuiteQL to seek out information for the Vendor that you really want:

HTTP Technique - POST

https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/question/v1/suiteql

//Ship the precise SuiteQL question beneath within the request physique
{
    "q": "SELECT * FROM Vendor the place vendorName="Take a look at Vendor 2""
}

What about customized entities and fields in REST?

That is barely simpler within the REST API as properly, as NetSuite provides a separate metadata catalog as a REST endpoint, and you may question (and persist if wanted) your entire schema of all objects.

This is a pattern REST API payload (you possibly can see how easy this appears in comparison with the SOAP-y mess we noticed earlier).

import requests
from requests_oauthlib import OAuth1

url="https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/report/v1/vendorBill"
auth = OAuth1('<consumer_key>', '<consumer_secret>', '<token>', '<token_secret>')

payload = {
    "entity": {"id": "12345"},
    "lineItems": [
        {"item": {"id": "5678"}, "quantity": 5},
        {"item": {"id": "9012"}, "quantity": 3}
    ]
}

response = requests.submit(url, json=payload, auth=auth)
print(response.json())

SOAP vs REST API: Which one must you use?

The cliched (however sadly, appropriate) reply is that it actually depends upon your use case. Whereas SOAP excels in environments requiring restricted transactions on customary objects and excessive safety, REST is most well-liked for its simplicity, flexibility and pace.

Benefits of the REST API

  • JSON Payloads: Straightforward to learn and debug, light-weight, and reduces bandwidth overhead.
  • Sooner Growth: You don’t must predefine strict buildings like SOAP’s WSDL.
  • Simpler to make use of SuiteQL: SuiteQL might be essentially the most highly effective side of NetSuite’s API, and is a breeze to make use of with REST. With SOAP, you might want to create a RESTlet to make use of SuiteQL.

Good Use Instances for the REST API

  • Light-weight deployments like cell apps or third social gathering functions the place primary CRUD operations (create, learn, replace and delete) have to be achieved at pace.
  • Complicated Workflows with Customized Information – Should you’re working with customised NetSuite information buildings, SuiteQL is by far one of the best ways to question and mix information. For instance, processes just like the beneath:
    • Approval workflows based mostly on customized fields, or
    • Customised 2-way/3-way PO matching

Benefits of the SOAP API

  • Dependable: Sturdy documentation and help since it’s a lot older.
  • Helps Saved Searches: One of many favorite methods of NetSuite customers to get filtered, custom-made information, this extends the Saved Search performance on to the API.

Good Use Instances for the SOAP API

  • Legacy deployments (like linking NetSuite to banking information) the place reliability and thoroughness of data is extra vital than pace.
  • Utilising Saved Searches – The SOAP API natively helps Saved Searches, that are a really helpful method of looking for information on the NetSuite UI. In case you are replicating Saved Searches and pushing that information into one other software, SOAP could be helpful.

You will discover much more element on the professionals/cons of every API in this weblog by Eric Popivker.


Setting Up the NetSuite API to make API calls

For the remainder of this text, we are going to use the REST API as the premise for dialogue (nevertheless lots of the similar processes will work with the SOAP API too).

Let’s undergo a step-by-step information to arrange the REST API and make an API name.

  1. Create an Integration Report:
    • In NetSuite, navigate to Setup > Integration > Handle Integrations > New.
    • Title your integration (e.g., “My REST API Integration”).
    • Examine “Token-Primarily based Authentication (TBA)” to allow it for the combination.
    • Save the report to generate the Client Key and Client Secret. You will want these for OAuth authentication.
  2. Assign Roles and Permissions:
    • Go to Setup > Customers/Roles > Entry Tokens > New.
    • Choose the combination you simply created.
    • Select the person and position (usually an admin or a task with the mandatory permissions to entry data through the API).
    • Generate the Token ID and Token Secret.
  3. OAuth Setup:
    • Create an entry token through Setup > Customers/Roles > Entry Tokens > New.
    • You’ll get a Token and Token Secret on your software.
    • NetSuite makes use of OAuth 1.0a for authentication. This requires the above 4 key parameters:
      • Client Key
      • Client Secret
      • Token ID
      • Token Secret

REST API Name Instance:

Your REST API calls will want each headers and physique (relying on the kind of request).

  • Headers:
    • Authentication: The first authentication is dealt with through OAuth 1.0a. You’ll move OAuth tokens within the header.
    • Content material-Sort: For POST or PUT requests, set this to software/json since NetSuite REST API works with JSON information.
Authorization: OAuth oauth_consumer_key="<consumer_key>",
                    oauth_token="<token>",
                    oauth_signature_method="HMAC-SHA1",
                    oauth_timestamp="<timestamp>",
                    oauth_nonce="<random_string>",
                    oauth_signature="<signature>"
Content material-Sort: software/json
  • Physique: The physique of the request is required when making POST or PUT requests, usually in JSON format. For instance, when making a buyer report, your physique may appear like this:
{
  "companyName": "ABC Corp",
  "electronic mail": "[email protected]",
  "telephone": "555-555-5555"
}

This is a full API name for instance:

import requests
from requests_oauthlib import OAuth1

url="https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/report/v1/buyer"
auth = OAuth1('<consumer_key>', '<consumer_secret>', '<token>', '<token_secret>')
headers = {
    'Content material-Sort': 'software/json'
}
information = {
    "companyName": "ABC Corp",
    "electronic mail": "[email protected]",
    "telephone": "555-555-5555"
}
response = requests.submit(url, json=information, auth=auth, headers=headers)
print(response.json())

Frequent points you may run into:

  • OAuth Setup: “Invalid signature” errors are widespread with OAuth 1.0a, usually brought on by incorrect parameter ordering or key misconfiguration.
  • Incorrect API URL: Be certain that you’re utilizing the proper NetSuite account ID within the API endpoint URL, e.g., https://<account_id>.suitetalk.api.netsuite.com.
  • 403 Forbidden: This could possibly be attributable to incorrect permissions or entry ranges for the person or position tied to the token.

Use an API testing software like Postman or Insomnia for simpler debugging and assist with API points.


Connecting NetSuite to different functions

NetSuite usually has pre-configured SuiteApp integrations and workflow instruments that may interface with numerous enterprise functions, together with:

  • CRM Instruments: Combine with Salesforce, HubSpot, or Zoho to sync buyer and gross sales information.
  • Office Apps: Instruments like Slack and Microsoft Groups could be built-in for real-time notifications or workflows.
  • E-commerce Platforms: Join NetSuite to platforms like Shopify or Magento for stock syncs and order administration.

This is a record of the highest integrations that exist for NetSuite as we speak.

There are additionally a number of software program platforms that usually assist you arrange drag-and-drop workflows with these integrations:

  • Celigo
  • Workato
  • MuleSoft
  • Boomi
Nanonets can join your approval course of to all the pieces else in your organization – throughout electronic mail, file storage, CRMs and buyer information.

When are these pre-built workflow integrations helpful?

You may resolve loads of enterprise issues with good integrations. Consider circumstances like:

  • Having to cross-check a buyer bill in NetSuite towards buyer information that is current in Salesforce/Hubspot
  • Having to manually enter information into NetSuite when scanning complicated payments/invoices as a result of the OCR template is model new and never recognised

However they might not resolve all of your issues. Contemplate the beneath scenario:

⚠️

It’s a must to ship out a NetSuite Vendor Invoice for division approval, however your workforce works solely on Slack and you may’t actually purchase a brand new NetSuite license for ALL of them to only approve a invoice.

One other widespread situation – your enterprise may depend on robust real-time stock monitoring. So that you arrange SuiteScripts to constantly monitor inventory ranges – however now it is impacting your NetSuite system efficiency.

Pre-built integrations go solely thus far, as we’ll discover out subsequent.


Why Use the NetSuite API if Pre-built Integrations Already Exist?

Pre-built workflow instruments and integrations simplify the setup for widespread use circumstances however fall quick in dealing with complicated, custom-made workflows. As an illustration, in the case of doing complicated processes at scale, you’ll most likely want to show to the API.

Let’s take an instance – say you may have a Buy Order matching course of the place you might want to match a PO to a number of vendor payments.

The usual NetSuite API has a perform referred to as PO Rework, that shall be current on many pre-built integrations and shall be built-in on the back-end code of most AP SaaS options.

This REST methodology has the beneath endpoint:

https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/report/v1/purchaseOrder/<purchase_order_internal_id>/!rework/vendorBill

You may name this API within the method beneath:

import requests
from requests_oauthlib import OAuth1

# NetSuite account info
account_id = '<account_id>'
purchase_order_id = '<purchase_order_internal_id>'
url = f'https://{account_id}.suitetalk.api.netsuite.com/providers/relaxation/report/v1/purchaseOrder/{purchase_order_id}/!rework/vendorBill'

# OAuth1 Authentication
auth = OAuth1('<consumer_key>', '<consumer_secret>', '<token>', '<token_secret>')

payload = {
    "entity": {
        "id": "<vendor_id>"
    },
    "memo": "Transformed from PO",
    "location": {  
        "id": "2"  
    },
    "lineItems": [  
        {
            "item": {"id": "1234"},  
            "quantity": 10, 
            "amount": 100.00 
        }
    ]
}

response = requests.submit(url, json=payload, auth=auth)

print(response.json())

The problem with the predefined methodology is that it’ll find yourself billing the ENTIRE Buy Order. There isn’t any method so that you can prohibit it by deciding on solely a part of the amount as per the Vendor Invoice.

So what’s the answer?


Constructing a posh workflow utilizing the API as a substitute of No-Code instruments

Let’s now exhibit a greater strategy to deal with the above scenario the place the pre-built integration fails. To attain our goal on this PO matching situation, we might want to use a SuiteQL question after which run a SuiteScript as beneath:

SuiteQL Question

SELECT id, merchandise, amount, quantity 
FROM transactionLine 
WHERE transactionType="PurchaseOrder" 
AND transaction.id = '12345';

This SQL-like question fetches information for a specific Buy Order, which you should utilize as enter for additional API calls or workflow automation. Notice that we needn’t iterate by way of EVERY buy order to get this achieved.

The REST API name for this SuiteQL question is:

curl -X POST https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/question/v1/suiteql 
-H "Authorization: OAuth oauth_consumer_key='<consumer_key>', oauth_token='<token>', oauth_signature="<signature>"" 
-H "Content material-Sort: software/json" 
-d '{
    "q": "SELECT id, merchandise, amount, quantity FROM transactionLine WHERE transactionType="PurchaseOrder" AND transaction.id = '12345';"
}'

SuiteScript for Creating Vendor Invoice

perform createVendorBill(poId) {
    var poRecord = report.load({
        sort: report.Sort.PURCHASE_ORDER,
        id: poId
    });

    var billRecord = report.create({
        sort: report.Sort.VENDOR_BILL
    });

    for (var i = 0; i < poRecord.getLineCount('merchandise'); i++) {
        var amount = poRecord.getSublistValue({ sublistId: 'merchandise', fieldId: 'amount', line: i });
        if (amount > 0) {
            billRecord.selectNewLine({ sublistId: 'merchandise' });
            billRecord.setCurrentSublistValue({ sublistId: 'merchandise', fieldId: 'merchandise', worth: poRecord.getSublistValue({ sublistId: 'merchandise', fieldId: 'merchandise', line: i }) });
            billRecord.setCurrentSublistValue({ sublistId: 'merchandise', fieldId: 'amount', worth: amount });
            billRecord.commitLine({ sublistId: 'merchandise' });
        }
    }
    billRecord.save();
}

This SuiteScript is customizable – you possibly can select to replace portions on the PO partially, or you possibly can select to by no means replace the PO till it’s totally matched throughout a number of invoices. The selection is totally yours.

You may set off this SuiteScript through the REST API as properly. Under is the pattern API name:

curl -X POST https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/script/v1/scriptexecution 
-H "Authorization: OAuth oauth_consumer_key='<consumer_key>', oauth_token='<token>', oauth_signature="<signature>"" 
-H "Content material-Sort: software/json" 
-d '{
    "scriptId": "customscript_create_vendor_bill",
    "deploymentId": "customdeploy_create_vendor_bill",
    "params": {
        "poId": "12345"
    }
}'

On this method you possibly can leverage the pliability of the NetSuite API, SuiteQL, and SuiteScript to automate complicated enterprise processes.

In case you are excited about going deeper into PO matching, this is a detailed information we printed on PO matching.


How one can run your API calls from an software

Whilst you can check API calls in Postman, you will have a extra organized strategy to work together with the NetSuite API and truly retailer and use the information you fetch.

To begin with, you possibly can arrange a small software in Python. Right here’s the fundamental setup for doing this:

Create a Python File:

import requests
from requests_oauthlib import OAuth1

def netsuite_api_call():
    url="https://<account_id>.suitetalk.api.netsuite.com/providers/relaxation/report/v1/buyer"
    auth = OAuth1('<consumer_key>', '<consumer_secret>', '<token>', '<token_secret>')
    response = requests.get(url, auth=auth)
    return response.json()

if __name__ == "__main__":
    print(netsuite_api_call())

Set up Required Libraries:

pip set up requests requests_oauthlib

Storing Information:

For one-off use circumstances, you may get by with storing information domestically in a JSON.

with open('netsuite_data.json', 'w') as file:
json.dump(information, file, indent=4)

For circumstances with extra information and common API calls to be achieved, you possibly can arrange a SQL database like SQLite3 utilizing the beneath pattern code.

import sqlite3

conn = sqlite3.join('netsuite_data.db')
cursor = conn.cursor()

cursor.execute('''
    CREATE TABLE IF NOT EXISTS prospects (
        id INTEGER PRIMARY KEY,
        identify TEXT,
        electronic mail TEXT
    )
''')

# Insert information into the database
for buyer in information['items']:
    cursor.execute('''
        INSERT INTO prospects (id, identify, electronic mail) 
        VALUES (?, ?, ?)
    ''', (buyer['id'], buyer['companyName'], buyer['email']))

conn.commit()
conn.shut()

Nevertheless past a sure level, you will want a manufacturing DB and a strategy to correctly administer and handle all this NetSuite information.


Deploying NetSuite APIs at Scale

Deploying NetSuite APIs at scale requires cautious consideration of efficiency, automation, and the layers of information you’re working with. Finish-to-end workflow automation instruments are typically one of the best match for this – they will enormously simplify this course of by offering an atmosphere that permits you to handle automation throughout completely different layers.

Automating Throughout 3 Information Layers

  1. Doc Layer:
    • This consists of processing paperwork like POs, invoices, financial institution statements, and vendor payments. Instruments usually use AI-enabled OCR and machine studying to extract information from these paperwork.
  2. AP Course of Layer:
    • The AP automation layer includes enterprise logic, akin to approval routing and matching paperwork like POs to invoices. Workflow instruments can automate the logic right here to automate these processes.
  3. ERP Layer:
    • The ERP layer refers back to the information and operations inside NetSuite itself. Utilizing NetSuite’s API, these workflow instruments can sync bi-directionally with NetSuite to push or pull information from the system, with out compromising the grasp information.

Nanonets is an AI workflow automation software that enables companies to orchestrate these layers in concord, enabling doc understanding, a easy AP course of, and sustaining a single supply of fact inside NetSuite.

Why Nanonets is Ideally suited for Scaling NetSuite API Utilization

  • Greatest-in-class AI enabled OCR: Information extraction that does not depend upon OCR templates and constantly learns from person inputs.
  • Enterprise Logic Automation: By permitting customized code deployment, Nanonets automates processes like bill matching, approval routing, and PO creation.
  • Deep ERP Sync: Interface in real-time with each single information level in NetSuite, together with customized objects and fields.

A pattern workflow with Nanonets just like the one beneath, takes solely 15-20 minutes to arrange.

Involved in studying extra? A brief 15-minute intro name with an automation skilled is one of the best ways to get began.


References:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles