The Full Information to Getting Began with the NetSuite API

0
18
The Full Information to Getting Began with the NetSuite API


Oracle NetSuite provides a strong API for integrating and lengthening your online business workflows, however working successfully with these APIs requires a stable understanding of how they operate.

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


Understanding NetSuite’s API Ecosystem

NetSuite began with the SuiteTalk SOAP API in 2002, which turned the go-to answer for companies seeking to combine their programs with NetSuite’s deep function set. For a few years, this was the usual API for NetSuite growth.

To deal with the eventual limitations within the SOAP API, NetSuite launched its REST API in 2019, providing an easier, extra scalable solution to entry knowledge. The REST API embraced trendy net requirements like JSON, offering simpler integration with cloud-native purposes 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 knowledge querying with SQL-like syntax. Because it seems, SuiteQL one of the crucial 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 loads of integrations will utilise the SOAP API just because it’s dependable and has good assist.

The API makes use of advanced XML payloads and has strict formatting, so whereas it’d initially appear good to have a excessive stage of element in each API name, it could possibly shortly grow to be cumbersome for instances the place it’s good to combine the APIs at some stage of scale.


  
123456 abc123 def456 random123 1627891230

NetSuite SOAP API payloads aren’t at all times developer-friendly.

Additional, all the metadata (principally the information about the NetSuite objects) is saved in a format known as WSDL (Net Providers Description Language). And the one metadata you get is that of the usual NetSuite objects and fields.

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

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

SuiteScript and RESTlets

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

💡

SuiteScript is a scripting language primarily based on JavaScript, that enables NetSuite builders (sure, that is you) to create personalized scripts and features that may be triggered on sure actions/occasions. It is a nifty solution to customise non-standard actions in NetSuite.

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

/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 */
outline(['N/record'], operate(file) {
    operate beforeSubmit(context) {
        var customerRecord = context.newRecord;
        
        // Set a brand new e mail tackle
        customerRecord.setValue({
            fieldId: 'e mail',
            worth: 'newemail@instance.com'
        });
    }
    
    return {
        beforeSubmit: beforeSubmit
    };
});

💡

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

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

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

The NetSuite REST API

Designed to be light-weight and extra suited to cloud-based apps, the REST API makes use of JSON payloads, lowering overhead in knowledge transmission. The transition from SOAP to REST mirrored the rising demand for easier, sooner, 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 usually a lot simpler. However in NetSuite’s case, this is not at all times true.

The article construction within the REST API is tough to take care of (owing partially to poor implementation of an object construction known as HATEOAS) which principally signifies that the information of an object just isn’t returned completely in a single go, however in nested hyperlinks.

Here is an instance – for those who 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 it’s good to know the ID of the seller you actually wish to get knowledge for.

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

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

What’s SuiteQL?

💡

SuiteQL is a question language (like SQL) that means that you can question the complete NetSuite knowledge construction. It is part of the NetSuite REST API, and a useful one at that.

In reality, 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 search out knowledge for the Vendor that you really want:

HTTP Technique - POST

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

//Ship the precise SuiteQL question under 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 nicely, as NetSuite provides 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 may 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://.suitetalk.api.netsuite.com/providers/relaxation/file/v1/vendorBill"
auth = OAuth1('', '', '', '')

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 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 commonplace 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 Improvement: You don’t have to predefine strict constructions 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, it’s good to create a RESTlet to make use of SuiteQL.

Good Use Circumstances for the REST API

  • Light-weight deployments like cell apps or third occasion purposes the place fundamental CRUD operations (create, learn, replace and delete) should be finished at velocity.
  • Advanced Workflows with Customized Knowledge – If you happen to’re working with customised NetSuite knowledge constructions, SuiteQL is by far one of the best ways 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 assist since it’s a lot older.
  • Helps Saved Searches: One of many favorite methods of NetSuite customers to get filtered, personalized knowledge, this extends the Saved Search performance on to the API.

Good Use Circumstances for the SOAP API

  • Legacy deployments (like linking NetSuite to banking knowledge) the place reliability and thoroughness of data is extra necessary than velocity.
  • Utilising Saved Searches – The SOAP API natively helps Saved Searches, that are a really helpful manner of looking for knowledge on the NetSuite UI. If you’re replicating Saved Searches and pushing that knowledge into one other utility, SOAP is perhaps 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 (nonetheless 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 File:
    • 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 mixing.
    • Save the file 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 mixing you simply created.
    • Select the consumer and function (usually an admin or a job with the required permissions to entry information 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 utility.
    • 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 by way of OAuth 1.0a. You’ll go OAuth tokens within the header.
    • Content material-Sort: For POST or PUT requests, set this to utility/json since NetSuite REST API works with JSON knowledge.
Authorization: OAuth oauth_consumer_key="",
                    oauth_token="",
                    oauth_signature_method="HMAC-SHA1",
                    oauth_timestamp="",
                    oauth_nonce="",
                    oauth_signature=""
Content material-Sort: utility/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 file, your physique would possibly appear to be this:
{
  "companyName": "ABC Corp",
  "e mail": "contact@abccorp.com",
  "cellphone": "555-555-5555"
}

Here is a full API name for instance:

import requests
from requests_oauthlib import OAuth1

url="https://.suitetalk.api.netsuite.com/providers/relaxation/file/v1/buyer"
auth = OAuth1('', '', '', '')
headers = {
    'Content material-Sort': 'utility/json'
}
knowledge = {
    "companyName": "ABC Corp",
    "e mail": "contact@abccorp.com",
    "cellphone": "555-555-5555"
}
response = requests.submit(url, json=knowledge, auth=auth, headers=headers)
print(response.json())

Frequent points you would possibly 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: Make sure that you’re utilizing the right NetSuite account ID within the API endpoint URL, e.g., https://.suitetalk.api.netsuite.com.
  • 403 Forbidden: This might be on account of incorrect permissions or entry ranges for the consumer or function 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 purposes

NetSuite usually has pre-configured SuiteApp integrations and workflow instruments that may interface with numerous 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 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.

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

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

When are these pre-built workflow integrations helpful?

You’ll be able to resolve loads of enterprise issues with good integrations. Consider instances 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 might not resolve all of your issues. Think about the under scenario:

⚠️

You must ship out a NetSuite Vendor Invoice for division approval, however your staff 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 state of affairs – your online business would possibly 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 instances however fall quick in dealing with advanced, personalized 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 could have a Buy Order matching course of the place it’s good to match a PO to a number of vendor payments.

The usual NetSuite API has a operate known as PO Remodel, 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 technique has the under endpoint:

https://.suitetalk.api.netsuite.com/providers/relaxation/file/v1/purchaseOrder//!rework/vendorBill

You’ll be able to name this API within the method under:

import requests
from requests_oauthlib import OAuth1

# NetSuite account data
account_id = ''
purchase_order_id = ''
url = f'https://{account_id}.suitetalk.api.netsuite.com/providers/relaxation/file/v1/purchaseOrder/{purchase_order_id}/!rework/vendorBill'

# OAuth1 Authentication
auth = OAuth1('', '', '', '')

payload = {
    "entity": {
        "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 technique is that it’ll find yourself billing the ENTIRE Buy Order. There isn’t any manner so that you can prohibit it by choosing solely a part of the amount as per the Vendor Invoice.

So what’s the answer?


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

Let’s now show a greater solution to deal with the above scenario the place the pre-built integration fails. To attain our goal on this PO matching state of affairs, 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://.suitetalk.api.netsuite.com/providers/relaxation/question/v1/suiteql 
-H "Authorization: OAuth oauth_consumer_key='', oauth_token='', oauth_signature=""" 
-H "Content material-Sort: utility/json" 
-d '{
    "q": "SELECT id, merchandise, amount, quantity FROM transactionLine WHERE transactionType="PurchaseOrder" AND transaction.id = '12345';"
}'

SuiteScript for Creating Vendor Invoice

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

    var billRecord = file.create({
        sort: file.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 may select to replace portions on the PO partially, or you may select to by no means replace the PO till it’s totally matched throughout a number of invoices. The selection is totally yours.

You’ll be able to set off this SuiteScript by way of the REST API as nicely. Beneath is the pattern API name:

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

On this manner you may leverage the flexibleness of the NetSuite API, SuiteQL, and SuiteScript to automate advanced enterprise processes.

In case you are desirous about going deeper into PO matching, here is a detailed information we printed.


The right way to run your API calls from an utility

Whilst you can take a look at API calls in Postman, you will want a extra organized solution to work together with the NetSuite API and truly retailer and use the information you fetch.

To start out with, you may arrange a small utility in Python. Right here’s the essential setup for doing this:

Create a Python File:

import requests
from requests_oauthlib import OAuth1

def netsuite_api_call():
    url="https://.suitetalk.api.netsuite.com/providers/relaxation/file/v1/buyer"
    auth = OAuth1('', '', '', '')
    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 Knowledge:

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

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

For instances with extra knowledge and common API calls to be finished, you may 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()

Nevertheless past a sure level, you may want a manufacturing DB and a solution 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 usually the very best match for this – they’ll tremendously simplify this course of by offering an atmosphere that means that you can handle automation throughout completely different layers.

Automating Throughout 3 Knowledge 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 knowledge from these paperwork.
  2. AP Course of Layer:
    • The AP course of layer includes enterprise logic, corresponding 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 software that enables companies to orchestrate these layers in concord, enabling doc understanding, a easy AP course of, and sustaining a single supply of reality inside NetSuite.

Why Nanonets is Perfect for Scaling NetSuite API Utilization

  • Greatest-in-class AI enabled OCR: Knowledge extraction that does not rely on OCR templates and constantly learns from consumer 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.

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


References:

LEAVE A REPLY

Please enter your comment!
Please enter your name here