Unit 8: APIs and how modern apps talk · Lesson 1 of 5 · 18 min

JSON APIs

The shop's mobile app talks to a JSON API. jq turns its answers into something you can read and query.

mission

You are
The analyst reviewing the shop's API.
Situation
The mobile app uses /api/v1/. Before reviewing it, you need to read its answers fluently.
Goal
Query the product endpoint and shape the JSON with jq.
Hand in
A one-line-per-product listing built from the API.

An API as a vending machine

01

Raw JSON

learner@web-lab
curl -s http://127.0.0.1:8000/api/v1/products
[{"id": 1, "name": "Padlock", "price": 12.5}, {"id": 2, "name": "Cable lock", "price": 18.0}, {"id": 3, "name": "Key safe", "price": 34.0}]

you should see One long line. Fine for programs, hard for people.

curl
Sends web requests and prints the response. Built into Linux, macOS and Windows 10 and later.
02

Pretty print

learner@web-lab
curl -s http://127.0.0.1:8000/api/v1/products | jq .
[
  {
    "id": 1,
    "name": "Padlock",
    "price": 12.5
  },
  {
...

you should see An array of objects, one per product.

jq
Picks fields out of JSON and reshapes it. Install with sudo apt install jq, or brew install jq on a Mac.
03

Pick and filter

learner@web-lab
curl -s http://127.0.0.1:8000/api/v1/products | jq 'length'
3
curl -s http://127.0.0.1:8000/api/v1/products | jq -r '.[] | select(.price > 15) | .name'
Cable lock
Key safe

you should see Three products, two of them over 15.

04

Shape a report line

learner@web-lab
curl -s http://127.0.0.1:8000/api/v1/products | jq -r '.[] | "\(.id) \(.name) \(.price)"'
1 Padlock 12.5
2 Cable lock 18.0
3 Key safe 34.0

you should see Plain text you can paste into notes or feed to other tools.

defender tip API reviews start with an inventory: every endpoint, its method, whether it needs a token and which fields it returns.

What a defender takes away

  1. 1APIs answer in JSON; jq is the grep and cut of JSON.
  2. 2jq . to read, select() to filter, string templates to report.
  3. 3Inventory endpoints and fields before reviewing anything else.

Questions

0 of 2 solved

Answer each one from what you find on your lab machine.