Getting responses from an endpoint using Background Scripts

KelseyMorri
Tera Contributor

How to get a response for an endpoint using background scripts?

 

This question was asked during an interview and the answer I gave was not correct. I assumed we could use JS and the sn_ws.RESTMessageV2  class to build out a REST message. Could someone give me the basics of how to do this? I cannot find any resources for responses from a specific endpoint. Thanks!

1 ACCEPTED SOLUTION

Sandeep Rajput
Tera Patron
Tera Patron

@KelseyMorri Here is an example of how you can call an API end point from a background script.

 

var r = new sn_ws.RESTMessageV2();
r.setEndpoint('https://api.example.com/data'); // Replace with your API URL
r.setHttpMethod('GET'); // Use 'POST', 'PUT', or 'DELETE' if needed

// Optional headers
r.setRequestHeader("Accept", "application/json");
r.setRequestHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN");

// Optional query parameters or body for POST/PUT
// r.setQueryParameter("key", "value");
// r.setRequestBody(JSON.stringify({ key: "value" }));

try {
  var response = r.execute();
  var responseBody = response.getBody();
  var httpStatus = response.getStatusCode();

  gs.info("HTTP Status: " + httpStatus);
  gs.info("Response Body: " + responseBody);

} catch (ex) {
  var message = ex.getMessage();
  gs.error("REST API call failed: " + message);
}

View solution in original post

3 REPLIES 3

Ankur Bawiskar
Tera Patron
Tera Patron

@KelseyMorri 

you can use REST Message in background script, parse the API response and get the details

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@KelseyMorri 

Thank you for marking my response as helpful.

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Sandeep Rajput
Tera Patron
Tera Patron

@KelseyMorri Here is an example of how you can call an API end point from a background script.

 

var r = new sn_ws.RESTMessageV2();
r.setEndpoint('https://api.example.com/data'); // Replace with your API URL
r.setHttpMethod('GET'); // Use 'POST', 'PUT', or 'DELETE' if needed

// Optional headers
r.setRequestHeader("Accept", "application/json");
r.setRequestHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN");

// Optional query parameters or body for POST/PUT
// r.setQueryParameter("key", "value");
// r.setRequestBody(JSON.stringify({ key: "value" }));

try {
  var response = r.execute();
  var responseBody = response.getBody();
  var httpStatus = response.getStatusCode();

  gs.info("HTTP Status: " + httpStatus);
  gs.info("Response Body: " + responseBody);

} catch (ex) {
  var message = ex.getMessage();
  gs.error("REST API call failed: " + message);
}