Error 400 while POST request with JSON

siddharthakadiy
Kilo Contributor

Hi all,

I am trying to send a JSON data through RESTMessage POST using the below steps:

1) I have set ${content} in the content body.

2) I have set http header 'Content-Type' as 'application/json'

3) I have added 'content' in the variable substitutions

In my script include I am using exactly the same code as shown in 'preview script usage' of that post request. Below is the code.

try {

var r = new sn_ws.RESTMessageV2('<Rest module name>', 'post');

r.setStringParameter('content', '{"assetBook":"abc","assetId":"222","assetNumber":"333","assetType":"xyz","description":"test","massAdditionId":"131"}');

var response = r.execute();

var responseBody = response.getBody();

var httpStatus = response.getStatusCode();

}

catch(ex) {

var message = ex.getMessage();

}

But I am getting a 400 http status response when i run it. I tried using the 'test' link in the post method page with the same data as test value and it works perfectly with 200 status. I am not able to figure out what the issue is as iam using exactly the same code given for preview script.

Please help.

Siddhartha

6 REPLIES 6

Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Pradeep,



Could you please help me out here, I am facing same error . When I hit Test in REST message getting 400 status code.


Mrman
Tera Guru

Hi Siddhartha,



Could you please let me know whether you were fix this issue , I am facing the same error 400 for REST message when I test it .Please help


Community Alums
Not applicable

Hi Siddhartha,



you are setting string as a value to content parameter. instead you have to build json object and set to that content variable.



you need to build json data like



var jsonObj = {};


jsonObj.assetBook="abc";


jsonObj.assetId="222";


jsonObj.assetNumber="333";


jsonObj.assetType="xyz";


jsonObj.description="test";


jsonObj.massAdditionId="131";





replace your code with below script.


=====================



try {


var r = new sn_ws.RESTMessageV2('<Rest module name>', 'post');.


r.setStringParameter('content', jsonObj);


var response = r.execute();


var responseBody = response.getBody();


var httpStatus = response.getStatusCode();


}


catch(ex) {


var message = ex.getMessage();


}



Thanks,


Rajendra Prasad Darshanam