2
$\begingroup$

I'd like to publish an api that returns an image as well as a number, but it seems that the docs for APIFunction specifies only a single possible format type:

enter image description here

Here's an example to play with:

randomClock[t_] := Rasterize[Graphics[Rotate[ClockGauge[t][[1]], 
     RandomReal[{0, 2 \[Pi]}], {0, 0}], ImagePadding -> 0], ImageSize -> 300];

randomClockDeploy[] := With[{t = RandomChoice /@ Range /@ {12, 60, 60}}, 
     {randomClock[t], t}]

CloudDeploy[APIFunction[{}, randomClockDeploy[] &], Permissions -> "Public"]

This returns:

enter image description here

So what I'm looking for would be something akin to:

CloudDeploy[APIFunction[{}, randomClockDeploy[] &, {"PNG","String"}], Permissions -> "Public"]

$\endgroup$
  • $\begingroup$ You should probably return a JSON object in that case. $\endgroup$ – chuy Apr 29 '16 at 18:33
  • $\begingroup$ Encoding the image inside the Json, can u show code to do this with my example? $\endgroup$ – M.R. Apr 29 '16 at 18:58
4
$\begingroup$

You can do something like this (encoding the PNG in Base64):

randomClock[t_] := 
  Rasterize[
   Graphics[
    Rotate[ClockGauge[t][[1]], RandomReal[{0, 2 \[Pi]}], {0, 0}], 
    ImagePadding -> 0], ImageSize -> 300];


randomClockDeploy[] := 
 With[{t = RandomChoice /@ Range /@ {12, 60, 60}}, <|
   "img" -> ExportString[randomClock[t], {"Base64", "PNG"}], 
   "text" -> ExportString[t, "Text"]|>]

CloudDeploy[
 APIFunction[{}, randomClockDeploy[] &, "JSON"], "clockJSON", 
 Permissions -> "Public"]

and a request to your API will receive this:

{
  "img": "iVBORw0KGgoAAAANSUh...EUgAA...kSuQmCC\n",
  "text": "7\n23\n38"
}

The "img" can be decoded by standard methods. In WL you would do:

ImportString[
 URLExecute[apiEndPoint, {}, "RawJSON"]["img"], {"Base64", "PNG"}]

Mathematica graphics

Alternatively, you can have the JSON object return the URL of the image:

randomClockDeploy2[] :=
 With[{t = RandomChoice /@ Range /@ {12, 60, 60}}, <|
   "img" -> 
    URLShorten@
     URLBuild[{CloudDirectory[], 
       Export["test.png", randomClock[t], "PNG"]}], 
   "text" -> ExportString[t, "Text"]|>]

now the API returns:

{
  "img": "https://wolfr.am/faKeShoRT",
  "text": "12\n16\n12"
}
$\endgroup$

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.