According to documentation, the setBody(body) method uses String in the param. But json is a string. If I have a body that I can successfully request using postman with json, how come I'm getting an error that the body is incorrect in salesforce?
This is the sample json class that is in Postman body as JSON
"name": "Apple MacBook Pro 16", "data": { "year": 2019, "price": 1849.99, "CPU model": "Intel Core i9", "Hard disk size": "1 TB" }
The code:
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.restful-api.dev/objects');
request.setMethod('POST');
request.setHeader('Content-Type', 'application/json');
String x = '{"name": "Apple MacBook Pro 16","data": {"year": 2019,"price": 1849.99,"CPU model": "Intel Core i9","Hard disk size": "1 TB"}';
String jsonString = JSON.serialize(x);
request.setBody(jsonString);
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
System.debug(response.getBody() + '' + response.getStatusCode());
The error log shows: Error: {"error":"400 Bad Request. If you are trying to create or update the data, potential issue is that you are sending incorrect body json or it is missing at all."}400
String x = '{"name": "Apple MacBook Pro 16","data": {"year": 2019,"price": 1849.99,"CPU model": "Intel Core i9","Hard disk size": "1 TB"}}';
You miss the}
at the end of the JSON.