Monday, January 20, 2025

The Full Information to Getting Began with the NetSuite API


Oracle NetSuite affords 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 situations. We’ll additionally discover how instruments like Nanonets might help automate your workflows throughout information layers.


Understanding NetSuite’s API Ecosystem

NetSuite began with the SuiteTalk SOAP API twenty 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 a less complicated, extra scalable solution to entry information. 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 information 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 right now a variety of 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 degree of element in each API name, it might rapidly turn out to be cumbersome for circumstances the place you should combine the APIs at some degree of scale.


  
123456 abc123 def456 random123 1627891230

NetSuite SOAP API payloads will not be at all times developer-friendly.

Additional, all the metadata (mainly the info 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 normal NetSuite modules, objects and fields.

So in the event you created any customized fields (or, god forbid, total customized objects) – you will not see them right here. There is a good means round this – utilizing RESTlets – however that may rapidly 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 primarily based on JavaScript, that permits 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 solution to customise non-standard actions in NetSuite.

Here is a pattern SuiteScript that updates the e-mail handle 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 electronic mail handle
        customerRecord.setValue({
            fieldId: 'electronic mail',
            worth: 'newemail@instance.com'
        });
    }
    
    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’ll be able to then use this information in one other software (like operating 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 performed, 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 suited to cloud-based apps, the REST API makes use of JSON payloads, lowering 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 utterly 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 partly to poor implementation of an object construction known as HATEOAS) which mainly implies that the info of an object just isn’t returned fully in a single go, however in nested hyperlinks.

Here is an instance – in the event you name a REST API endpoint like /distributors you’d usually count on 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 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 should 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 means 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 whole NetSuite information construction. It is part of the NetSuite REST API, and a useful one at that.

Actually, 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 information 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 beneath 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 properly, as NetSuite provides a separate metadata catalog as a REST endpoint, and you’ll question (and persist if wanted) the whole schema of all objects.

Here 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://.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.publish(url, json=payload, auth=auth)
print(response.json())

SOAP vs REST API: Which one do you have to use?

The cliched (however sadly, right) 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 popular 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 have to predefine strict constructions like SOAP’s WSDL.
  • Simpler to make use of SuiteQL: SuiteQL might be essentially the most highly effective facet 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 Circumstances 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) have to be performed at pace.
  • Advanced Workflows with Customized Knowledge – Should you’re working with customised NetSuite information constructions, SuiteQL is by far one of the simplest ways to question and mix information. For instance, processes just like the beneath:
    • Approval workflows primarily based 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 Circumstances for the SOAP API

  • Legacy deployments (like linking NetSuite to banking information) the place reliability and thoroughness of knowledge is extra necessary than pace.
  • Utilising Saved Searches – The SOAP API natively helps Saved Searches, that are a really helpful means 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 most of the identical 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”).
    • Test “Token-Primarily based Authentication (TBA)” to allow it for the combination.
    • 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 combination you simply created.
    • Select the consumer and function (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 cross 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="",
                    oauth_token="",
                    oauth_signature_method="HMAC-SHA1",
                    oauth_timestamp="",
                    oauth_nonce="",
                    oauth_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 file, your physique may appear like this:
{
  "companyName": "ABC Corp",
  "electronic mail": "contact@abccorp.com",
  "telephone": "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': 'software/json'
}
information = {
    "companyName": "ABC Corp",
    "electronic mail": "contact@abccorp.com",
    "telephone": "555-555-5555"
}
response = requests.publish(url, json=information, auth=auth, headers=headers)
print(response.json())

Frequent points you may run into:

  • OAuth Setup: “Invalid signature” errors are frequent with OAuth 1.0a, typically attributable to 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 could possibly be on account of incorrect permissions or entry ranges for the consumer 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 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 information.
  • 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 right now.

There are additionally a number of software program platforms that usually make it easier 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 electronic mail, file storage, CRMs and buyer information.

When are these pre-built workflow integrations helpful?

You’ll be able to resolve a variety 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 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. Take into account the beneath 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’ll’t actually purchase a brand new NetSuite license for ALL of them to only approve a invoice.

One other frequent state of affairs – your online business may depend on sturdy 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 date, 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 frequent use circumstances however fall brief in dealing with advanced, custom-made workflows. As an illustration, relating to doing advanced processes at scale, you’ll most likely want to show to the API.

Let’s take an instance – say you have got 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 operate known as PO Rework, that will probably be current on many pre-built integrations and will probably be built-in on the back-end code of most AP SaaS options.

This REST technique has the beneath endpoint:

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

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

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.publish(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 a means so that you can limit it by choosing solely a part of the amount as per the Vendor Invoice.

So what’s the answer?


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

Let’s now display a greater solution to deal with the above state of affairs 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 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 need to use as enter for additional API calls or workflow automation. Observe that we needn’t iterate by EVERY buy order to get this performed.

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: software/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 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’ll be able to set off this SuiteScript through the REST API as properly. Under 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: software/json" 
-d '{
    "scriptId": "customscript_create_vendor_bill",
    "deploymentId": "customdeploy_create_vendor_bill",
    "params": {
        "poId": "12345"
    }
}'

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

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


Tips on how to run your API calls from an software

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

To start out with, you possibly can arrange a small software 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 circumstances, you will 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 performed, 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 clients (
        id INTEGER PRIMARY KEY,
        identify TEXT,
        electronic mail TEXT
    )
''')

# Insert information into the database
for buyer in information['items']:
    cursor.execute('''
        INSERT INTO clients (id, identify, electronic 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 solution 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 usually the very best match for this – they will tremendously simplify this course of by offering an setting that permits you to handle automation throughout totally different layers.

Automating Throughout 3 Knowledge Layers

  1. Doc Layer:
    • This contains 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, 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 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 device that permits 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 Excellent for Scaling NetSuite API Utilization

  • Greatest-in-class AI enabled OCR: Knowledge extraction that does not rely on OCR templates and repeatedly 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 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 professional is one of the simplest ways to get began.


References:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles

PHP Code Snippets Powered By : XYZScripts.com