Page 1 of 1

POST JSON to API with HTTP Request

Posted: Thu Nov 29, 2018 8:16 am
by mart3223
Good morning forum members,

Does anyone of you have the experience with posting a JSON to an API with basic aut. I'm continuously getting a 404 error in switch. I'm trying to send a customer address to a shipping provider: https://docs.sendcloud.sc/api/v2/index. ... e-a-parcel. Currently I'm making a JSON with "make JSON" and send that with the "HTTP request" to the API. Does anyone have created a similar link? How does you're flow look like, and where are you putting te information.

Thanks a lot.

Martijn

Re: POST JSON to API with HTTP Request

Posted: Thu Nov 29, 2018 5:30 pm
by cstevens
I haven't used make JSON or basic authentication, but I've created a couple scripts that do authenticated RESTful API calls.

One takes a .json input file and just attaches it to the HTTP client using:

Code: Select all

httpClient.setAttachedFile(jsonBodyLoc);  //where jsonBodyLoc is the location of the incoming JSON file (job.getPath())
httpClient.addHeader("Content-Type", "application/json");
httpClient.post();
Most RESTful APIs give some kind of detail on the failure, so I capture the response with

Code: Select all

var responseJSON = httpClient.getServerResponse().toString("UTF-8");
Then write that to the logs in case of error.

The other script has very simple JSON bodies so I just create it as a string in the script using property values in the script. Then I write it to a temp file and attach it to the HTTP Client like I did above. Something like this:

Code: Select all

var jsonBodyLoc = job.createPathWithName("folder.json");
var jsonFile = new File(jsonBodyLoc);		
var jsonString = "{\"name\": \"" + s.getPropertyValue("name") + "\", \"from\": \"" + s.getPropertyValue("from") + "\", \"to\": \"" + s.getPropertyValue("to") + "\"}";
jsonFile.open(File.WriteOnly);
jsonFile.write(jsonString);
jsonFile.close();

Re: POST JSON to API with HTTP Request

Posted: Thu Nov 29, 2018 7:44 pm
by mart3223
cstevens wrote: Thu Nov 29, 2018 5:30 pm I haven't used make JSON or basic authentication, but I've created a couple scripts that do authenticated RESTful API calls....
Great thanks, but you are using the scripting module I guess?

Re: POST JSON to API with HTTP Request

Posted: Thu Nov 29, 2018 10:08 pm
by cstevens
Yes, I have to do custom authentication so I don't have a choice.

Re: POST JSON to API with HTTP Request

Posted: Thu Feb 07, 2019 1:50 pm
by mart3223
cstevens wrote: Thu Nov 29, 2018 10:08 pm Yes, I have to do custom authentication so I don't have a choice.
Ah great, got it working right now. Problem solved. JSON was corrupt ;)