Code of PUT Scripted rest API

NikitaGupta02
Tera Contributor

Hello team,

 

I need to create the update the record via put scripted rest AP. Can anyone help me in this like how can we write the script for this and what will be the endpoint and payload for this?

 

Best Regards,

Nikita

7 REPLIES 7

Viraj Hudlikar
Tera Sage

Hello @NikitaGupta02 


Follow below steps

1) Create a Scripted REST API by using path as System Web Services > Scripted Web Services > Scripted REST APIs.

2) Define the API. In this provide name and api id.

3) Create a Resource

  • Click on the Resources tab and then New to create a new resource.
  • Name: Update Record
  • HTTP Method: PUT
  • Path: /update/{table}/{sys_id}

4) Write the Script: Example script is given below to update a record on any table.

 

 var tableName = request.pathParams.table;
    var recordSysId = request.pathParams.sys_id;
    var requestBody = request.body.data;
var gr = new GlideRecord(tableName);
    if (gr.get(recordSysId)) {
        for (var field in requestBody) {
            if (requestBody.hasOwnProperty(field)) {
                gr.setValue(field, requestBody[field]);
            }
        }
        gr.update();
        response.setStatus(200);
        response.setBody({ message: 'Record updated successfully', sys_id: recordSysId });
    } else {
        response.setStatus(404);
        response.setBody({ error: 'Record not found' });
    }

 

 

5) Endpoint and Payload:

Endpoint: https://<your_instance>.service-now.com/api/update_record_api/update/<table>/<sys_id>   

Payload: The payload should be a JSON object containing the fields you want to update. For example:
 {
     "short_description": "Updated description",
     "priority": "2"
 }

6) Test API:  Use a tool like Postman to send a PUT request to the endpoint with the payload. Ensure you have the necessary authentication headers (e.g., Basic Auth or OAuth).

 

If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.

Hello @NikitaGupta02 

 

In RESTful API design, the PUT method is typically used to update an existing resource, while the POST method is used to create a new resource. However, you can technically use the insert function within a PUT method in ServiceNow if you want to allow the creation of a new record when the specified record does not exist. This approach is sometimes referred to as an "upsert" (update or insert).

 

Here's how you can modify the Scripted REST API to handle both updating an existing record and inserting a new one if the record does not exist:

var tableName = request.pathParams.table;
    var recordSysId = request.pathParams.sys_id;
    var requestBody = request.body.data;

    var gr = new GlideRecord(tableName);
    if (gr.get(recordSysId)) {
        // Update existing record
        for (var field in requestBody) {
            if (requestBody.hasOwnProperty(field)) {
                gr.setValue(field, requestBody[field]);
            }
        }
        gr.update();
        response.setStatus(200);
        response.setBody({ message: 'Record updated successfully', sys_id: recordSysId });
    } else {
        // Insert new record
        gr.initialize();
        for (var field in requestBody) {
            if (requestBody.hasOwnProperty(field)) {
                gr.setValue(field, requestBody[field]);
            }
        }
        var newSysId = gr.insert();
        response.setStatus(201);
        response.setBody({ message: 'Record created successfully', sys_id: newSysId });
    }


If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.

Viraj,  I am trying to do a similar thing following your example however the record never gets updated.  

This is my code.

 

var recordNumber = request.pathParams.number;
var requestBody = request.body.data;
var inc_gr = new GlideRecord('incident');
if(inc_gr.get('number',recordNumber))
{
    for (var field in requestBody)
    {
       
        if(requestBody.hasOwnProperty(field))
        {
            inc_gr.setValue(field, requestBody[field]);
            gs.log("RestAPI field:"+field+" value:"+requestBody[field] + "hasProperty"+requestBody.hasOwnProperty(field),"BWLAPI");
        }

    }
    inc_gr.update();

    response.setStatus(200);
    response.setBody({message:'Record updated successfully'});
}
    else
    {
        response.setStatus('404');
        response.setBody({error:'Record not found'});
    }

Hello @Brent L_1 

 

Ensure that the field names in the requestBody match exactly with the field names in the 'incident' table. Any mismatch will prevent the fields from being updated.
Try to add more detailed logging to understand what's happening at each step by using gs.log()

Ensure that the user making the API call has the necessary permissions to update records in the 'incident' table.
The status code for the "Record not found" case should be set as a number, not a string.

Revised code:

var recordNumber = request.pathParams.number;
var requestBody = request.body.data;
var inc_gr = new GlideRecord('incident');

if (inc_gr.get('number', recordNumber)) {
    gs.log("Record found: " + recordNumber, "BWLAPI");
    for (var field in requestBody) {
        if (requestBody.hasOwnProperty(field)) {
            inc_gr.setValue(field, requestBody[field]);
            gs.log("RestAPI field: " + field + " value: " + requestBody[field], "BWLAPI");
        }
    }
    inc_gr.update();
    gs.log("Record updated successfully: " + recordNumber, "BWLAPI");
    response.setStatus(200);
    response.setBody({ message: 'Record updated successfully' });
} else {
    gs.log("Record not found: " + recordNumber, "BWLAPI");
    response.setStatus(404);
    response.setBody({ error: 'Record not found' });
}

 Also, try updating different records to ensure the issue isn't specific to a particular record.

Look at the API logs in ServiceNow to see if there are any errors or warnings that might provide more insight.

If my response has helped you hit helpful button and if your concern is solved do mark my response as correct.

 

Thanks & Regards
Viraj Hudlikar.