Group Abstract Group Abstract

Message Boards Message Boards

1
|
7.7K Views
|
3 Replies
|
2 Total Likes
View groups...
Share
Share this post:

What types of HTTP POST an API function in the Cloud can deal with?

Posted 4 years ago
POSTED BY: Clarisse Wagner
3 Replies
Posted 6 months ago

It sounds like you want the APIFunction to use the request body and parse it as JSON.

The first argument to APIFunction is the list of parameters, which are obtained either from query parameters or as you first indicated, or from parameters in the request body using application/x-www-form-urlencoded or multipart/form-data. APIFunction and FormFunction automatically detect these from the HTTP request to populate the parameters.

This explains the error you got, about not finding the "Chiffre" parameter.

You can do what you want, you just need to access the request body (through HTTPRequestData) and parse it (through ImportString), and additionally, not declare any parameters (by providing an empty list as the first argument). Here's the end-to-end code:

api = CloudPublish[
  APIFunction[{}, 
   StringSplit[
     ImportString[FromCharacterCode[HTTPRequestData["BodyBytes"]], 
       "RawJSON"]["Chiffre"]] &]]
requestData = {"Chiffre" -> "Il neige au Printemps"};
requestBody = ExportByteArray[requestData, "JSON"];
URLRead[HTTPRequest[api, <|"Body" -> requestBody|>], "Body"]

Additionally, if you want to test the APIFunction without the cloud, you would use GenerateHTTPResponse, and supply a 2nd argument so you can specify the request body:

GenerateHTTPResponse[
  APIFunction[{}, 
   StringSplit[
     ImportString[FromCharacterCode[HTTPRequestData["BodyBytes"]], 
       "RawJSON"]["Chiffre"]] &],
  <|"BodyBytes" -> 
    ToCharacterCode[
     ExportString[{"Chiffre" -> "Il neige au Printemps"}, "JSON"], 
     "UTF-8"]|>
  ]["Body"]
POSTED BY: Joel Klein

Pinging this old discussion to note that Wolfram's APIFunction only accepts the application/x-www-form-encoded content type. It doesn't accept JSON directly.

The only alternative I can think of within Wolfram is using Wolfram Data Drop, which does accept JSON input.

POSTED BY: Steven Buehler
Posted 2 years ago

Did you manage to crack the code by now?

POSTED BY: Smoothur Alex
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard