NetSuite RESTlet: A Practical POST Example
Hey guys! Ever felt like wrestling with NetSuite to get data in and out just the way you need it? That's where RESTlets come in super handy. Think of them as your custom APIs within NetSuite, tailored to do exactly what you want. Today, we're diving deep into crafting a NetSuite RESTlet that accepts data via a POST request. Trust me; by the end of this, you'll be equipped to handle data submissions like a pro.
Understanding RESTlets
Before we get our hands dirty with code, let's quickly recap what RESTlets are and why they're awesome. RESTlets are server-side JavaScript scripts in NetSuite that you can expose as RESTful web services. This means you can interact with NetSuite data using standard HTTP methods like GET, POST, PUT, and DELETE. For our example, we're focusing on POST, which is typically used for creating new records or submitting data to NetSuite.
Why RESTlets? They give you the flexibility to build custom integrations, automate processes, and extend NetSuite's functionality beyond its standard features. Plus, they're incredibly powerful when you need to integrate NetSuite with other systems or applications.
Setting the Stage: Our Use Case
Let's say we want to create a RESTlet that allows us to create new customer records in NetSuite from an external application. Our RESTlet will accept customer data (like name, email, and phone number) via a POST request and then create a new customer record in NetSuite with that data. This is a common scenario, and it's a great way to illustrate how RESTlets work.
Designing the RESTlet Script
First things first, we need to create a new RESTlet script in NetSuite. Navigate to Customization > Scripting > Scripts > New. Give your script a name (e.g., Customer Creation RESTlet) and make sure to select RESTlet as the script type. Now, let's dive into the code.
/**
 * @NApiVersion 2.x
 * @NScriptType Restlet
 */
define(['N/record', 'N/log'],
    function(record, log) {
        function doPost(context) {
            try {
                log.debug({title: 'Context', details: context});
                var request = JSON.parse(context.body);
                var customerRecord = record.create({type: record.Type.CUSTOMER, isDynamic: true});
                customerRecord.setValue({fieldId: 'firstname', value: request.firstName});
                customerRecord.setValue({fieldId: 'lastname', value: request.lastName});
                customerRecord.setValue({fieldId: 'email', value: request.email});
                customerRecord.setValue({fieldId: 'phone', value: request.phone});
                var recordId = customerRecord.save();
                log.debug({
                    title: 'Record created successfully',
                    details: 'Id: ' + recordId
                });
                return {status: 'success', recordId: recordId};
            } catch (e) {
                log.error({
                    title: 'Error creating record',
                    details: e.toString()
                });
                return {status: 'error', message: e.toString()};
            }
        }
        return {
            post: doPost
        };
    });
Let's break down this code:
- @NApiVersion 2.x: Specifies the NetSuite API version we're using.
- @NScriptType Restlet: Declares that this script is a RESTlet.
- define(['N/record', 'N/log'], function(record, log) { ... });: This is the AMD (Asynchronous Module Definition) format. It imports the- N/recordand- N/logmodules, which we'll use to create records and log messages, respectively.
- doPost(context): This is the function that will be executed when the RESTlet receives a POST request. The- contextobject contains the data sent in the request body.
- JSON.parse(context.body): Parses the JSON data from the request body.
- record.create({type: record.Type.CUSTOMER, isDynamic: true}): Creates a new customer record in dynamic mode, which allows us to set field values one by one.
- customerRecord.setValue({fieldId: 'firstname', value: request.firstName}): Sets the value of the- firstnamefield on the customer record. We repeat this for- lastname,- email, and- phone.
- customerRecord.save(): Saves the new customer record to NetSuite.
- The try...catchblock handles any errors that might occur during the process. Error logging is crucial for debugging.
Deploying the RESTlet
Once you've saved your script, you need to create a script deployment. Go to Customization > Scripting > Script Deployments > New. Select your Customer Creation RESTlet script. Give the deployment a name (e.g., Customer Creation RESTlet Deployment).
- Important: Make sure to set the Status to Released. This makes the RESTlet accessible.
- Under the Audience tab, specify who can access the RESTlet. For testing purposes, you can set it to All Roles, but in a production environment, you'll want to restrict access to specific roles.
- Save the deployment. NetSuite will generate an External URL. This is the URL you'll use to send POST requests to your RESTlet. Keep this URL safe and secure! Anyone with this URL can potentially create customer records.
Testing the RESTlet with a POST Request
Now comes the fun part: testing our RESTlet. You can use tools like Postman, Insomnia, or even curl to send POST requests. Here's an example using curl:
curl -X POST \
  'YOUR_RESTLET_URL' \
  -H 'Content-Type: application/json' \
  -d '{