Show Menu
Cheatography

ServiceNow REST - Cheat Sheet Cheat Sheet by

REST API in ServiceNow

REST API Basics

Scripted REST APIs

API URIs
This part the for the scripted rest has to define name_s­pace, api_id, resour­ce_­path, version
API Query Parameter
When defining a scripted resource, which parameter is mandatory for the request can also be defined
API Error Objects*
Scripted REST APIs provide multiple ways to send an error in a response to a requesting client.
*Multiple error objects are available in scripted REST API scripts to report error inform­ation to requesting client­s.All scripted REST API error objects use the sn_ws_err namespace.
Error objects available are 400,40­4,4­06,­409,415

REST API Best Practices

Follow REST API Conven­tions
REST API conven­tions define specific behaviour for each type of method. For ex : GET : to Query the data, POST : to create Data,PUT and PATCH : to Update data, DELETE : to delete records.
Use Versioning to control changes to API
Use versioning to implement new functi­ona­lities, so that the existing functi­ona­lities will not impact
Return an Inform­ative HTTP Status code
Return a status code, which inform the requestor about the success and failur­es(­defined in the response codes section)
Return useful error inform­ation
Provide the requestor with enough inform­ation of why the failure occurred. Error message is a mix of error message and error code
Enforce and test Access Controls
Enforce existing access controls and require additional access to modify the data. Use the GlideR­eco­rdS­ecure* API in scripted RESI services
Build Tests to verify functi­onality
Tests should validate the response code, headers, and body content as approp­riate for each resource you implement. You can also use tests to validate authen­tic­ation requir­ements, and to confirm that errors return useful responses.
*Glide­Rec­ord­Secure API Ensure that the ACLs are defined on the underlying data are applied to the requested user.

REST Security

How is REST API Secure?
The REST API uses basic authen­tic­ation or OAuth to enforce access controls to web resources. ACLs are defined on tables to restrict the data viewer­ship.
Will all tables be available for the REST API Access?
By default, Yes. All tables including system tables, and scoped tables are available.
How can I restrict a table Access through web services?
In the table proper­ties, uncheck the option for Allow access to this table via web services.
Does REST API support CORS?
Cross Origin Resource Security is supported.
How can I Define CORS Rules?
CORS Rules can be defined in sys_co­rs_­rule. Which allows to specify a domain and Selection of methods to expose.
How to disable CORS Support for Instance?
CORS support on instance is defined by glide.r­es­t.c­ors.en­abled set it to false for No CORS
Can I use OAuth with REST?
Yes, use OAuth token for REST Requests
Can I use MFA with REST?
Yes again, with a REST Request, if MFA is enabled then append token to end of users password ex:use­rid­:pa­ssw­rdt­oken. Encode using base64 encoding
 

Building Blocks REST API

API
API allows to select a specific Applic­ation Progra­mming interface, which is available in SNOW
Ex TableA­PI,­Agg­reg­ateAPI
Namespace
REST APIs provided by ServiceNow has now namespace
Scripted REST may use a different one
Method
REST enables the use of few methods like GET,POST,DELETE,PATCH
Not all the APIs available from ServiceNow would have all the methods available
Request Header
Allows to specify a header for the Integr­ation
Can add Custom header as per requir­ement
Query parameter
Allows to specify an encoded query for the REST Call
Can add more query parameters or even a sys_id for some methods
You can prepare the sample request using the REST API Explorer in Servic­eNow.
ServiceNow REST URI looks like this <LI­NKF­ORS­NOW­>/a­pi/­now­/ap­iname/. For ex : if we are using a table API for POST then the link look something like below : POST <LI­NKO­FSe­rvi­ceN­ow>­/ap­i/n­ow/­tab­le/­tab­lename

REST API Rate Limit

To prevent excessive inbound REST API requests, set rules that limit the number of inbound REST API requests processed per hour.

There is an option to create Rate Limit for users with specific roles, or for all users. The table for creating rate limit is sys_ra­te_­lim­it_­rules.

In the basic Response Header, the Rate limit would be specified for ex : x-Rate­Lim­it-­Limit -->10

REST API Headers

Accept
applic­ati­on/­json, applic­ati­on/xml
Conten­t-Type
pplica­tio­n/json, applic­ati­on/xml
By design, POST, PUT, PATCH, and DELETE operations required to provide both headers.
GET operations require only the Accept header.
There is an option override the HTTP method, such as GET or POST, by setting the X-http­-me­tho­d-o­verride header.

REST API Response Codes

200
Success
Success with Response Body
201
Created
Success with Response Body
204
Success
Success with Response Body
400
Bad Request
The Request URI can't match the API.
Invalid headers, or API incorrect
401
Unauth­orized
The User is not authorized to use API
403
Forbidden
The Operation requested is not permitted for the user
ACL constraint on table, Business Rule or data policies
404
Not Found
The requested resource is not found
ACL constraint or resource not available
405
Method not allowed
The HTTP action is not allowed or not supported by the API
406
Not acceptable
The endpoint doesn't support the response format
Response format in the Request Accept Header
415
Unsupp­orted media type
The endpoint does not support the format of the request body.

RESTMe­ssageV2

execute()
Sends the REST message to Endpoint
execut­eAs­ync()
Sends the REST message asynch­ron­ously, that means the instance doesn't wait for a response from provider
getEnd­point()
Get the URL of the endpoint for the REST message.
getReq­ues­tBody()
Get the content of the REST message body.
getReq­ues­tHe­ade­r(<­hea­der­nam­e>)*
Get the value for an HTTP header specified in the REST message.
getReq­ues­tHe­aders()
Get HTTP headers that were set by the REST client and the associated values.
saveRe­spo­nse­Bod­yAs­Att­ach­men­t(t­bln­ame­,re­cor­did­,fi­len­ame)**
Configures the REST message to save the returned response body as an attachment record.
saveRe­spo­nse­Bod­yAs­Att­ach­men­t(t­bln­ame­,re­cor­did­,fi­len­ame­,en­cry­ptc­ontext)*
Configure the REST message to save the returned response body as an encrypted attachment record.
setAut­hen­tic­ati­onP­rof­ile­(ty­pe,­pro­fileid)**
Set the creden­tials for the REST message using an existing basic auth or OAuth 2.0 profile.
setBas­icA­uth­(us­ern­ame­,pa­ssword)
Sets basic authen­tic­ation headers for the REST message.
setEcc­Cor­rel­ato­r(c­orr­elator)
Associate outbound requests and the resulting response record in the ECC queue. This method only applies to REST messages sent through a MID Server.
setEcc­Par­ame­ter­(na­me,­value)
Override a value from the database by writing to the REST message payload. This method only applies to REST messages sent through a MID Server.
setEnd­poi­nt(­end­point)
Set the endpoint for the REST message.
setHtt­pMe­tho­d(m­ethod)
The HTTP method this REST message performs, such as GET or PUT.
setHtt­pTi­meo­ut(­mil­lis­econds)
Set the amount of time the REST message waits for a response from the web service provider before the request times out.
setLog­Lev­el(­level)
Set the log level for this message and the corres­ponding respon­se.V­alid values for level are basic, elevated, and all.
setMID­Ser­ver­(mi­dse­rver)
The name of the MID Server to use. Your instance must have an active MID Server with the specified name.
setMut­ual­Aut­h(p­rof­ile­name)
Set the mutual authen­tic­ation protocol profile for the REST message.
setQue­ryP­ara­met­er(­name, value)
Append a parameter to the end of the request URL with the form name=v­alue.
setReq­ues­tBo­dy(­body)
Set the body content to send to the web service provider when using PUT or POST HTTP methods.
setReq­ues­tBo­dyF­rom­Att­ach­men­t(a­tta­chm­ent­sysid)
Sets the request body using an existing attachment record.
setReq­ues­tHe­ade­r(n­ame­,va­lue);
Set an HTTP header in the REST message to the specified value.
setReq­ues­tor­Pro­fil­e(r­equ­est­orc­ont­ext­,re­que­storid)
Override the default requestor profile for the REST message in order to retrieve an OAuth access token associated with a different requestor.
setStr­ing­Par­ame­ter­(na­me,­value)
Set a REST message function variable with the specified name from the REST message record to the specified value.
setStr­ing­Par­ame­ter­NoE­sca­pe(­nam­e,v­alue)
XML reserved characters in the value are converted to the equivalent escaped charac­ters.
waitFo­rRe­spo­nse­(se­conds)
In seconds. Wait at most 60 seconds to get response from ECC Queue/Mid Server.
*By design, this method cannot return the value for a header set automa­tically by the system. To grant this method access to all headers, set the property glide.h­tt­p.l­og_­debug to true.
**the input parameters for this functions are string, and recordId is the sysid of the record
*encryp­tco­ntext should specify the sysid of the encryption context
 

Comments

very informative

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Service-Now Client Side Cheats Cheat Sheet
          ServicePortal Cheat Sheet Cheat Sheet

          More Cheat Sheets by bibingokuldas

          Service-Now Client Side Cheats Cheat Sheet
          ServicePortal Cheat Sheet Cheat Sheet
          Key API ServiceNow Scripts Cheat Sheet