6
$\begingroup$

How to make APIFunction get its parameters from the body?

By default it uses the request URI, which is first insecure, and second, won't allow me to pass e.g. images to the function.

$\endgroup$
4
  • $\begingroup$ Is something like APIFunction[{}, HTTPRequestData["Body"] &] acceptable? $\endgroup$
    – chuy
    Jun 10, 2016 at 15:42
  • $\begingroup$ It also depends on how you are planning on making the request. What headers are you using? $\endgroup$
    – chuy
    Jun 10, 2016 at 15:59
  • $\begingroup$ @chuy, thanks, this is exactly what I need. I expected it to be somewhere in the association. Write an answer and I will accept it $\endgroup$ Jun 10, 2016 at 16:03
  • $\begingroup$ Perhaps your question is answered by APIFunction on Images. $\endgroup$ Jun 10, 2016 at 19:28

1 Answer 1

8
$\begingroup$

Ultimately the body can be extracted by using HTTPRequestData

HTTPRequestData[]

will return an Association containing properties and values. Usually you can specify the specific property you want, like "Body" (I seem to remember some issues getting "MultipartElements" at some point in time).

obj = CloudDeploy[APIFunction[{}, HTTPRequestData["Body"] &]]

URLExecute[obj, {}, 
  "Body" -> "\"test body\"",
  "Headers" -> {"content-type" -> "text/plain" (*or whatever is appropriate*)}, 
  Method -> "POST"]
"test body" 

If your API is actually attached to a form, and your header when making the request is something like:

Content-Type: multipart/form-data

you can use the following

CloudDeploy[APIFunction[{"i"-> "Image"}, #i &,"PNG"]]

This will echo back the image "i" (as labeled in your form). I put "PNG" for display purposes, you should change it to fit your needs.

$\endgroup$
4
  • $\begingroup$ With your addition of POST I'm getting Missing["NotAvailable"]. $\endgroup$
    – Kuba
    Jun 10, 2016 at 22:42
  • $\begingroup$ @Kuba: ugh you are right, but without it that means its making a GET request. I am going to look for a workaround. The URLExecute/URLFetch functions are a mess. $\endgroup$
    – chuy
    Jun 13, 2016 at 13:22
  • $\begingroup$ Yep, I wasn't investigating closer but GET was my concern too. I find them a little bit chaotic too but I blame my limited experience in the area. Looking forward for news from your side then :) $\endgroup$
    – Kuba
    Jun 13, 2016 at 13:24
  • $\begingroup$ @Kuba: it looks like the header needs to be specified. I suppose that isn't too unreasonable, but I would think it would fall back to "text/plain" by default. $\endgroup$
    – chuy
    Jun 13, 2016 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.