Computing Foundations › APIs and the Web › Day 28

Day 28: Consuming a Public API from the Command Line

Day 28 of 365 — Consuming a Public API from the Command Line

After this lesson you will be able to read an API's documentation and build a working client from scratch — form the request, send it with curl, parse the JSON reply, handle errors and rate limits, and present the result — the exact motion every AI API call needs.

Course
Computing Foundations
Category
APIs and the Web
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-028-consuming-a-public-api-from-the

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-028-consuming-a-public-api-from-the
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: the parts of a URL query string


Historical background


What it is — and what it is not

It is:

It is not:


Why it was created and what problems it solves


How it works

The six-stage pipeline

  1. Read the docs. Find the endpoint, the required and optional parameters, the authentication rule, and the shape of the response.

  2. Build the request. Assemble the URL and its query string — ? to start, & between name=value pairs.

  3. Send it. One command. curl fetches and prints the raw response.

  4. Parse the JSON. Pull out the fields you want with jq or python3.

  5. Handle errors. Check the request actually succeeded and the field was present, so a blip or a typo produces a clear message rather than garbage.

  6. Present the result. A clean, readable line.

Flowchart: the six stages of an API client, from reading the docs to presenting the result

Reading the docs is the core skill

Diagram: the four questions to answer when reading API documentation

Every API’s documentation answers the same four questions:

From curl to jq to a report

curl -s "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current=temperature_2m,wind_speed_10m"
{
  "current_units": { "temperature_2m": "°C", "wind_speed_10m": "km/h" },
  "current": { "time": "2026-07-12T12:30", "temperature_2m": 29.5, "wind_speed_10m": 16.9 }
}
curl -s "https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&current=temperature_2m,wind_speed_10m" \
  | jq '.current.temperature_2m'

The two tools, and their alternatives


An everyday analogy

Diagram: the checks to make on an API response before using it

Diagram: adapting a documented example compared with writing from scratch

Cooking from an unfamiliar recipe.

The kitchenThe client
Reading the recipe firstReading the docs
Checking you have the ingredientsRequired parameters
Following it exactly, onceRunning their example verbatim
Then adjusting one thingChanging one parameter at a time
Tasting as you goChecking the response at each stage
Plating itPresenting the result

Examples in practice

Diagram: why checking the HTTP status before parsing matters

Diagram: the anatomy of a single API call from URL to extracted field


Implications: security, privacy, performance, scalability, and cost

Diagram: the characteristic failure of each stage of an API client


Alternatives: free, open source, and commercial

Diagram: the essential jq operations

ToolTypeWhere it fits
curl + jqFree, ubiquitousExploring, debugging, and plenty of real automation
httpieFree, open sourceExploring by hand, with better ergonomics
python3 + requestsFree, open sourceThe moment you need logic, retries or tests
python3 -m json.toolFree, built inPretty-printing with nothing installed
Official SDKsUsually freeProduction use of a specific service
Postman / InsomniaFree tiersSaved collections and team sharing

TermWhat it actually is
Query string?name=value&name=value appended to a path
-sSilent: suppress curl’s progress meter
jq pathA route into nested JSON, read left to right
-rRaw output: strings without their quotes
Exit codeHow your script knows whether the call worked
PipelineDay 10’s idea, applied to an API response

When to use it — and when not to

Diagram: when a curl one-liner graduates to a script and then to a real program


The AI connection

Diagram: the signals that a shell client has outgrown the shell


Knowledge check

quiz:
  question: "A pipeline that fetches JSON and extracts a field with `jq` starts printing parse errors. The endpoint works in a browser. What should you check first?"
  options:
    - "The HTTP status code, since an error response body is often HTML rather than JSON"
    - "The jq path, since the response structure has probably changed"
    - "The shell quoting on the URL, since & would background the command"
    - "The Content-Type header, since jq requires it to be set correctly"
  answer_index: 0
  explanation: "jq is being handed something that is not JSON, and the usual reason is that the request failed — a 429, a 500, or an authentication error whose body is an HTML page. Checking the status before parsing turns a baffling parse error into a clear one."

Hands-on exercise

Build the client one stage at a time, adding error handling as you go. Worked through fully in the Day 28 lab directory.

What you are doingCommand
Fetch and lookcurl -s "$URL"
Pretty-print itcurl -s "$URL" | python3 -m json.tool
Extract one fieldcurl -s "$URL" | jq '.current.temperature_2m'
Strip the quotescurl -s "$URL" | jq -r '.current.time'
Capture the status toocurl -s -w '\n%{http_code}' "$URL"
Fail on an error statuscurl -sf "$URL" || echo "request failed"
Present itprintf '%s°C, wind %s km/h\n' "$t" "$w"

Expected output

29.5
2026-07-12T12:30
200
request failed
29.5°C, wind 16.9 km/h

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. In the six-stage API client pipeline, what is the correct order of the stages?

  1. Send, read the docs, build the request, present, parse, handle errors
  2. Build the request, read the docs, parse, send, present, handle errors
  3. Read the docs, build the request, send, parse the JSON, handle errors, present
  4. Parse the JSON, send, build the request, read the docs, present, handle errors
Show answer

Answer: C. Read the docs, build the request, send, parse the JSON, handle errors, present

Every client follows the same path: read the documentation, build the request from it, send it with curl, parse the JSON reply, handle whatever went wrong, and present a clean result. Each stage feeds the next.

Q2. Why must you wrap an API URL in double quotes when it contains a query string like ?a=1&b=2?

  1. Quotes make the request run faster
  2. Quotes encrypt the URL before sending it
  3. curl cannot read a URL longer than one parameter unless it is quoted
  4. A bare & means background, so curl gets only the first parameter
Show answer

Answer: D. A bare & means background, so curl gets only the first parameter

An unquoted & tells the shell to run the command in the background, cutting the URL off after the first parameter. Double quotes pass the whole URL, & and ? included, to curl intact.

Q3. Given the response {"current": {"temperature_2m": 12.4}}, which jq path prints 12.4?

  1. jq '.current.temperature_2m'
  2. jq '.current'
  3. jq '.temperature_2m'
  4. jq 'temperature_2m.current'
Show answer

Answer: A. jq '.current.temperature_2m'

A jq path reads left to right through the nesting: enter the current object, then take its temperature_2m field. The path mirrors exactly how the field is nested in the JSON.

Q4. Which statement about free public APIs is correct?

  1. Every public API requires an API key before you can call it
  2. Some public APIs need no key at all
  3. Free APIs never return JSON, only plain text
  4. You must install a special library to call any public API
Show answer

Answer: B. Some public APIs need no key at all

Many excellent public APIs are "no-key": Open-Meteo, Open Notify, and JSONPlaceholder all respond to an anonymous request, which is why they are ideal for learning the request-and-parse loop.

Q5. What is the single most transferable skill in consuming any new API?

  1. Memorizing every endpoint of the service
  2. Writing the client in a compiled language
  3. Reading the docs to find endpoints and parameters
  4. Guessing the field names until one works
Show answer

Answer: C. Reading the docs to find endpoints and parameters

You are never expected to memorize an API. Every API's docs answer the same four questions — endpoint, parameters, auth, response shape — so learning to read that contract makes any new service usable in minutes.

Q6. Your curl command prints nothing at all. Which is the best first thing to check?

  1. Reinstall curl from scratch
  2. Delete your parse step and hope it works
  3. Assume the API has permanently shut down
  4. Run the raw curl command alone first
Show answer

Answer: D. Run the raw curl command alone first

Isolate the stages: run the raw curl first. If it prints JSON, the fetch works and the problem is in your parse; if it prints nothing, the request or the network is the issue — check quoting and add --max-time to fail fast.

Q7. When should a curl one-liner graduate into a real program with an HTTP client library?

  1. When logic grows: loops, retries, branching, or several calls
  2. Never — a shell one-liner can do anything a program can
  3. Immediately — one-liners are never appropriate for real work
  4. Only when the API starts requiring a key
Show answer

Answer: A. When logic grows: loops, retries, branching, or several calls

Start at the command line to understand an API, then move the request into code exactly when the problem outgrows a single readable line — loops, retries, real error branching, or combining calls. The request itself does not change.

Q8. Why is consuming a weather API called the direct prerequisite for every AI API call in the course?

  1. Weather models and language models use the same training data
  2. Calling an AI model is the same motion with a different URL and body
  3. AI APIs return weather data by default
  4. Language models can only be reached through weather services
Show answer

Answer: B. Calling an AI model is the same motion with a different URL and body

A language-model call is this exact pattern: send a request to the model's endpoint, attach a JSON body describing the prompt, add an Authorization header, and parse the JSON reply. Endpoint, parameters, headers, auth, parse — every piece is what you practice on a free weather API.

Glossary

API client
A program — even a single command — that sends a request to a remote service and uses the response it gets back. Today you build one for weather.
endpoint
The URL a request is sent to, naming the specific resource or operation you want, like an address on an envelope.
query parameter
A name=value pair carried in the URL after a ?, joined by &, that specifies the details of your request (for example latitude=52.52).
JSON parsing
Pulling the fields you want out of a JSON response by their path, so a larger reply becomes the one or two values your program needs.
jq
A command-line tool that reads JSON structurally and extracts fields by path (for example .current.temperature_2m), the way grep extracts lines by pattern.
curl
A small, ubiquitous command-line program that makes an HTTP request to a URL and prints the response — the standard way to send an API call from a terminal.
error handling
Checking whether a request actually succeeded and whether the expected field was present, so a failure produces a clear message instead of garbage or a crash.
free tier
A level of an API that costs nothing to use within stated limits; free public APIs like Open-Meteo make them ideal for learning without a bill.
no-auth API
A public API that requires no key or token to call — anyone can send an anonymous request and get a response, as with Open-Meteo, Open Notify, and JSONPlaceholder.
request pipeline
The six repeatable stages of any API client: read the docs, build the request, send it, parse the JSON, handle errors, and present the result.
HTTP client library
A library inside a programming language (such as Python's requests or JavaScript's built-in fetch) that sends HTTP requests from code, used when a shell one-liner outgrows a single line.
documentation
The reference an API publishes describing its endpoints, parameters, authentication, and response shape; reading it is the core transferable skill of consuming any API.
rate limit
A cap a service places on how many requests you may send in a period; a polite client stays within it, spacing requests and honoring any Retry-After header.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.