Wolfram Language

Cloud & Web Interfaces

Create an Animal Spotting Application

A RESTful API uses the same URL but responds differently depending on the HTTP method. GenerateHTTPResponse works recursively, so a Delayed computation can return different instances of APIFunction to handle different HTTP methods to implement a location report web application.

Create a simple app that collects locations where different types of animals have been spotted.

In[1]:=
Click for copyable input
animallocator = Delayed[ With[{query = HTTPRequestData["Query"]}, Switch[HTTPRequestData["Method"], "POST", APIFunction[{"what" -> "Animal", "where" -> "Location" :> $GeoLocation}, (PutAppend[{#where, #what}, "locations.m"]; "Thank you for your submission.") &], "GET", APIFunction[{"zoom" -> Restricted["Integer", {1, 18}] -> 14}, GeoGraphics[ Map[GeoMarker[First[#], Tooltip[Last[#]["Image"], Last[#]], "Scale" -> Offset[80]] &, Quiet[Check[ReadList["locations.m"], {}]]], GeoZoomLevel -> #zoom, ImageSize -> 700] &, "PNG"], _, HTTPErrorResponse[400] ] ]];

Simulate reporting some animal sightings.

In[2]:=
Click for copyable input
GenerateHTTPResponse[ animallocator, <|"Method" -> "POST", "Query" -> {"what" -> "coyote", "where" -> "40.083449,-88.200732"}|>]; GenerateHTTPResponse[ animallocator, <|"Method" -> "POST", "Query" -> {"what" -> "buffalo", "where" -> "40.140722, -88.195257"}|>]; GenerateHTTPResponse[ animallocator, <|"Method" -> "POST", "Query" -> {"what" -> "beaver", "where" -> "40.063029,-87.9870"}|>]; GenerateHTTPResponse[ animallocator, <|"Method" -> "POST", "Query" -> {"what" -> "reindeer", "where" -> "40.29778, -88.2023"}|>]; GenerateHTTPResponse[animallocator, <|"Method" -> "POST", "Query" -> {"what" -> "gopher", "where" -> "40.116420,-88.243383"}|>]
Out[2]=

Simulate fetching the results.

In[3]:=
Click for copyable input
ImportString[GenerateHTTPResponse[animallocator]["Body"], "PNG"]
Out[3]=

Related Examples

de es fr ja ko pt-br ru zh