-7 C
New York
Monday, December 23, 2024

The Full Information to Getting Began with the NetSuite API


Oracle NetSuite affords a robust API for integrating and lengthening your online business 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 purposes, and scaling your deployments – all whereas leveraging NetSuite’s SuiteQL and SuiteScript for extra advanced situations. We’ll additionally discover how instruments like Nanonets might help automate your workflows throughout knowledge 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 resolution for companies seeking to combine their techniques with NetSuite’s deep characteristic set. For a few years, this was the usual API for NetSuite improvement.

To deal with the eventual limitations within the SOAP API, NetSuite launched its REST API in 2019, providing a less complicated, extra scalable method to entry knowledge. The REST API embraced trendy net requirements like JSON, offering simpler integration with cloud-native purposes and APIs. Nonetheless, 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 knowledge querying with SQL-like syntax. Because it seems, SuiteQL one of the vital 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 at this time numerous integrations will utilise the SOAP API just because it’s dependable and has good help.

The API makes use of advanced XML payloads and has strict formatting, so whereas it would initially appear good to have a excessive stage of element in each API name, it may possibly rapidly grow to be cumbersome for circumstances the place you should combine the APIs at some stage 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 at all times developer-friendly.

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

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

What are RESTlets? Earlier than we go additional, let’s perceive a number of NetSuite API ideas (be happy to skip forward in case you are already effectively versed).

SuiteScript and RESTlets

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

💡

SuiteScript is a scripting language primarily based 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 method to customise non-standard actions in NetSuite.

Here is a pattern SuiteScript that updates the e-mail deal with of a buyer document in NetSuite:

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

💡

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

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

Nonetheless, creating and scaling RESTlet utilization is cumbersome. It may be finished, however wants a devoted place to host your code and enterprise logic + maintain monitor 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 knowledge transmission. The transition from SOAP to REST mirrored the rising demand for easier, sooner, and extra accessible integrations, notably 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 at all times true.

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

Here is an instance – should you name a REST API endpoint like /distributors you’ll usually anticipate one thing like this within the response:

{
    {
      "vendorId": "123abc",
      "vendorName": "Check Vendor"
    },
    {
      "vendorId": "123abcd",
      "vendorName": "Check Vendor 2"
    },
    {
      "vendorId": "123abcde",
      "vendorName": "Check Vendor 3"
    } 
}

As an alternative, what you get is a set of IDs of every vendor, and API hyperlinks to the person vendor entities themselves. So now you should know the ID of the seller you actually wish to get knowledge for.

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

There’s a approach 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 the complete NetSuite knowledge construction. It is part of the NetSuite REST API, and a useful one at that.

The truth is, there’s a whole separate endpoint within the REST API to name SuiteQL. Let’s take the instance above – here is how you need to use SuiteQL to seek out knowledge for the Vendor that you really want:

HTTP Technique - POST

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

//Ship the precise SuiteQL question under within the request physique
{
    "q": "SELECT * FROM Vendor the place vendorName="Check Vendor 2""
}

What about customized entities and fields in REST?

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

Here is a pattern REST API payload (you possibly can see how easy this appears to be like 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/companies/relaxation/document/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.put up(url, json=payload, auth=auth)
print(response.json())

SOAP vs REST API: Which one do you have to 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 normal objects and excessive safety, REST is most well-liked for its simplicity, flexibility and velocity.

Benefits of the REST API

  • JSON Payloads: Straightforward to learn and debug, light-weight, and reduces bandwidth overhead.
  • Quicker Growth: You don’t have to 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 should 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 purposes the place primary CRUD operations (create, learn, replace and delete) should be finished at velocity.
  • Advanced Workflows with Customized Information – For those who’re working with customised NetSuite knowledge buildings, SuiteQL is by far the easiest way to question and mix knowledge. For instance, processes just like the under:
    • Approval workflows primarily based on customized fields, or
    • Customised 2-way/3-way PO matching

Benefits of the SOAP API

  • Dependable: Robust 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 knowledge, this extends the Saved Search performance on to the API.

Good Use Instances for the SOAP API

  • Legacy deployments (like linking NetSuite to banking knowledge) the place reliability and thoroughness of knowledge is extra essential than velocity.
  • Utilising Saved Searches – The SOAP API natively helps Saved Searches, that are a really helpful approach of looking for knowledge on the NetSuite UI. In case you are replicating Saved Searches and pushing that knowledge 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 most 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”).
    • Verify “Token-Primarily based Authentication (TBA)” to allow it for the combination.
    • Save the document to generate the Shopper Key and Shopper 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 function (sometimes an admin or a task with the mandatory permissions to entry data by way of the API).
    • Generate the Token ID and Token Secret.
  3. OAuth Setup:
    • Create an entry token by way of 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:
      • Shopper Key
      • Shopper 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 by way of OAuth 1.0a. You’ll cross OAuth tokens within the header.
    • Content material-Kind: For POST or PUT requests, set this to software/json since NetSuite REST API works with JSON knowledge.
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-Kind: software/json
  • Physique: The physique of the request is required when making POST or PUT requests, sometimes in JSON format. For instance, when making a buyer document, your physique may appear like this:
{
  "companyName": "ABC Corp",
  "e mail": "[email protected]",
  "cellphone": "555-555-5555"
}

Here is a full API name for instance:

import requests
from requests_oauthlib import OAuth1

url="https://<account_id>.suitetalk.api.netsuite.com/companies/relaxation/document/v1/buyer"
auth = OAuth1('<consumer_key>', '<consumer_secret>', '<token>', '<token_secret>')
headers = {
    'Content material-Kind': 'software/json'
}
knowledge = {
    "companyName": "ABC Corp",
    "e mail": "[email protected]",
    "cellphone": "555-555-5555"
}
response = requests.put up(url, json=knowledge, auth=auth, headers=headers)
print(response.json())

Widespread points you may run into:

  • OAuth Setup: “Invalid signature” errors are widespread with OAuth 1.0a, usually attributable to incorrect parameter ordering or key misconfiguration.
  • Incorrect API URL: Be sure 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 might be because of incorrect permissions or entry ranges for the person or function tied to the token.

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


Connecting NetSuite to different purposes

NetSuite sometimes has pre-configured SuiteApp integrations and workflow instruments that may interface with varied enterprise purposes, together with:

  • CRM Instruments: Combine with Salesforce, HubSpot, or Zoho to sync buyer and gross sales knowledge.
  • Office Apps: Instruments like Slack and Microsoft Groups may 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.

Here is a listing of the highest integrations that exist for NetSuite at this time.

There are additionally a number of software program platforms that sometimes provide help to arrange drag-and-drop workflows with these integrations:

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

When are these pre-built workflow integrations helpful?

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

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

However they could not resolve all of your issues. Think about the under state of affairs:

⚠️

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

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

Pre-built integrations go solely to this point, 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 brief in dealing with advanced, custom-made workflows. As an example, in relation to doing advanced processes at scale, you’ll in all probability want to show to the API.

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

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

This REST methodology has the under endpoint:

https://<account_id>.suitetalk.api.netsuite.com/companies/relaxation/document/v1/purchaseOrder/<purchase_order_internal_id>/!remodel/vendorBill

You may name this API within the method under:

import requests
from requests_oauthlib import OAuth1

# NetSuite account data
account_id = '<account_id>'
purchase_order_id = '<purchase_order_internal_id>'
url = f'https://{account_id}.suitetalk.api.netsuite.com/companies/relaxation/document/v1/purchaseOrder/{purchase_order_id}/!remodel/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.put up(url, json=payload, auth=auth)

print(response.json())

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

So what’s the resolution?


Constructing a fancy workflow utilizing the API as an alternative of No-Code instruments

Let’s now display a greater method to deal with the above state of affairs the place the pre-built integration fails. To realize our goal on this PO matching situation, we might want to use a SuiteQL question after which run a SuiteScript as under:

SuiteQL Question

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

This SQL-like question fetches knowledge for a specific Buy Order, which you need to use as enter for additional API calls or workflow automation. Observe that we needn’t iterate by means of EVERY buy order to get this finished.

The REST API name for this SuiteQL question is:

curl -X POST https://<account_id>.suitetalk.api.netsuite.com/companies/relaxation/question/v1/suiteql 
-H "Authorization: OAuth oauth_consumer_key='<consumer_key>', oauth_token='<token>', oauth_signature="<signature>"" 
-H "Content material-Kind: 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 = document.load({
        sort: document.Kind.PURCHASE_ORDER,
        id: poId
    });

    var billRecord = document.create({
        sort: document.Kind.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 by way of the REST API as effectively. Under is the pattern API name:

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

On this approach you possibly can leverage the flexibleness of the NetSuite API, SuiteQL, and SuiteScript to automate advanced enterprise processes.

In case you are occupied with going deeper into PO matching, here is a detailed information we printed on PO matching.


The best way to run your API calls from an software

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

To start out 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/companies/relaxation/document/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 will get by with storing knowledge regionally in a JSON.

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

For circumstances with extra knowledge and common API calls to be finished, you possibly can arrange a SQL database like SQLite3 utilizing the under 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,
        e mail TEXT
    )
''')

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

conn.commit()
conn.shut()

Nonetheless past a sure level, you will want a manufacturing DB and a method to correctly administer and handle all this NetSuite knowledge.


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 the most effective match for this – they will enormously simplify this course of by offering an surroundings that permits you to handle automation throughout totally 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 sometimes use AI-enabled OCR and machine studying to extract knowledge from these paperwork.
  2. AP Course of Layer:
    • The AP automation layer includes enterprise logic, similar 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 knowledge and operations inside NetSuite itself. Utilizing NetSuite’s API, these workflow instruments can sync bi-directionally with NetSuite to push or pull knowledge from the system, with out compromising the grasp knowledge.

Nanonets is an AI workflow automation device 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 Ultimate for Scaling NetSuite API Utilization

  • Greatest-in-class AI enabled OCR: Information extraction that does not rely on OCR templates and repeatedly 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 knowledge level in NetSuite, together with customized objects and fields.

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

Fascinated by studying extra? A brief 15-minute intro name with an automation skilled is the easiest way to get began.


References:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles