I started writing another post, but wound up writing a non-trivial script for
working with Phoenix JSON APIs.
That script is covered in this post.
It is written for the FreeBSD Bourne shell, but it should be compatible with bash.
This post also serves as a getopts example.
getopts was used instead of getopt because getopt does not support
command line arguments that contain spaces.
Create a new Phoenix project.
This example will use a JSON memo service.
Revise the web/router.ex file.
The “/api” scope needs to be uncommented and the “/memos” route needs to be added.
Run the migration.
Tests should pass.
Running the Sample Project
Start the server.
The following curl commands can be used to interact with the JSON API.
A script is easier to use if you need to make more than a couple of curl calls.
It can also be extended to support authentication and everything else your API may need.
Create a script to GET, POST, PATCH, PUT and DELETE memos.
Note that a Bourne Shell tutorial can be found here.
The reset function resets the variables to their initial state.
It is called before parsing command line arguments and displaying the usage.
The usage function displays usage, options and examples.
It also terminates the script.
The getopts loop parses command line arguments into variables.
The case statement at the end uses the HTTP method to select a curl call.
The GET method works with or without an id.
The POST method creates a payload and posts it.
PUT is like post except the verb is different and it requires an id.
PATCH is the most complicated.
It builds a payload and strips the trailing comma.
Then it sends the payload to a URL with an id.
DELETE requires an id.
The script can be used as follows.
Note that trying to delete a memo that does not exist will fail with a wall of HTML.
This script could be customized to work with other APIs.