Solution for Chapter 1: Getting Started with API First
Design and Build Great Web APIs — by Mike Amundsen (112 / 127)
--
👈 Where’s the Code? | TOC | 2: HTTP, REST, and APIs 👉
In the Chapter Exercise, the task is to use the curl command-line tool to pull a series of responses from three related services (company, account, and activity) and save them to disk for later reference. Here is a step-by-step solution.
First, create a folder called services on your local drive and then change directories to move into that newly created services folder:
mca@mamund-ws:~/$ mkdir services
mca@mamund-ws:~/$ cd services
mca@mamund-ws:~/services$
Next, using the list supplied in the Chapter Exercise, as a guide, start to pull the API responses from the services and save them to disk. Here’s one way to do this:
mca@mamund-ws:~/services$ curl /
https://company-atk.herokuapp.com/company > company-home.json
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 77 100 77 0 0 11 0 0:00:07 0:00:06 0:00:01 18
mca@mamund-ws:~/services$
The resulting data saved in the file company-home.json will look like this:
{"home" : {"name":"company", "rel" : "collection", "href":"/company/list/"}}
You can also use curl in a few other ways to get the same results. Here are some other examples:
mca@mamund-ws:~/services$ curl \
https://company-atk.herokuapp.com/company/list \
--output company-list.json
mca@mamund-ws:~/services$ curl -X GET \
https://company-atk.herokuapp.com/company/21r1aeuj87e \
> company-record.json
This exercise has a total of seven URLs. When you’re done calling all of them, you should have a services folder that looks like this:
mca@mamund-ws:~/services$ ls
account-list.json
account-record.json
activity-list.json
activity-record.json
company-home.json
company-list.json
company-record.json
You can check the files in the completed folder to compare your API output to the output on the disk.
Design and Build Great Web APIs by Mike Amundsen can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.