Thursday, September 12, 2019

RESTful Web APIS, by Leonard Richardson & Mike Amundsen has an example in chapter 2 (A Simple API) on calling a HTTP Get using wget, but does not show how to call the Post using the same tool.

From the book:

$ wget -S -O - http://www.youtypeitwepostit.com/api/

calls the API with a Get and displays the output to the console (I'm using Termux in Android)

The response includes a template to be used when calling the Post method, so to save typing I called the Get again but saved the response to a file (msg)

$ wget -S -O msg http://www.youtypeitwepostit.com/api/

Then edited the response file in nano - still in Termux to just contain the body of my Post, and saved as msg1

{
    "template" : {
        "data" : [
            {"prompt" : "Text of message", "name" : "text", "value" : "wibble"}
         ]
    }
}



The wget command for the Post is:

$ wget --post-file=msg1 -S -O - --header="Content-Type: application/vnd.collection+json" http://www.youtypeitwepostit.com/api/

Which results in a 201 response and the URL to the newly created message on the server:

  HTTP/1.1 201 Created
  Server: Cowboy
  Connection: keep-alive
  Location: http://www.youtypeitwepostit.com/api/5486216361168772
  Date: Thu, 12 Sep 2019 04:06:23 GMT
  Transfer-Encoding: chunked
  Via: 1.1 vegur


Additional:
wget installed in Termux by "pkg install wget"
nano installed in Termux by "pkg install nano"