We've updated the ServiceNow Community Code of Conduct, adding guidelines around AI usage, professionalism, and content violations. Read more

How to use Custom Header in REST API in serviceNow

Neeraj Modi
Tera Guru

We have a requirement to send a custom header, key value pair in the scripted REST API and the second servicenow instance should be able to read the custom header.

 

I am using the below shown script but nothing I am able to achieve so far.

 

Any help here will be much appricicated. 

var request = new sn_ws.RESTMessageV2();
request.setEndpoint('<EndPoint>');
request.setHttpMethod('GET');

//Eg. UserName="admin", Password="admin" for this code sample.
var user = 'admin';
var password = 'admin';

request.setBasicAuth(user,password);
request.setRequestHeader("Accept","application/json");
request.setRequestHeader("Test-Header", "CustomHeaderValue");

var response = request.execute();

gs.log("getBody --> " + response.getBody()); //Getting Body
gs.log("getStatusCode --> " + response.getStatusCode()); //Getting 200
gs.log("getRequestHeader -->  " + response.getRequestHeader()); //Getting undefined
gs.log("getRequestHeaders -->  " + response.getRequestHeaders()); //Getting undefined
gs.log("getHeaders --> " + JSON.stringify(response.getHeaders())); //Getting other headers but not the custom one.
gs.log("getAllHeaders --> " + response.getAllHeaders()); //Getting other headers but not the custom one.

 

 

1 ACCEPTED SOLUTION

Kieran Anson
Kilo Patron

You need to call getRequestHeaders() on the request variable, not the response.

gs.log("getBody --> " + response.getBody()); //Getting Body
gs.log("getStatusCode --> " + response.getStatusCode()); //Getting 200
gs.log("getRequestHeader -->  " + request.getRequestHeader('header_key_here')); //Getting undefined
gs.log("getRequestHeaders -->  " + request.getRequestHeaders()); //Getting undefined
gs.log("getHeaders --> " + JSON.stringify(request.getHeaders())); //Getting other headers but not the custom one.
gs.log("getAllHeaders --> " + response.getAllHeaders()); //Getting other headers but not the custom one.

View solution in original post

1 REPLY 1

Kieran Anson
Kilo Patron

You need to call getRequestHeaders() on the request variable, not the response.

gs.log("getBody --> " + response.getBody()); //Getting Body
gs.log("getStatusCode --> " + response.getStatusCode()); //Getting 200
gs.log("getRequestHeader -->  " + request.getRequestHeader('header_key_here')); //Getting undefined
gs.log("getRequestHeaders -->  " + request.getRequestHeaders()); //Getting undefined
gs.log("getHeaders --> " + JSON.stringify(request.getHeaders())); //Getting other headers but not the custom one.
gs.log("getAllHeaders --> " + response.getAllHeaders()); //Getting other headers but not the custom one.