Course outline · 0% complete

0/25 lessons0%

Course overview →

APIs: HTTP for programs

lesson 4-4 · ~11 min · 13/25

The web without the pages

Browsers are not the only HTTP clients. Most HTTP traffic today is programs talking to programs: your phone's weather app fetching a forecast, a checkout page asking a payment company's servers to charge a card, one company's backend pulling shipping rates from another's. These program-facing services are APIs (Application Programming Interfaces), and building and calling them is a large share of what working software engineers do all week.

An API exists because a program needs data, not a rendered page. GET /weather/lisbon on an API answers with the temperature as structured data a program can use, instead of HTML meant for human eyes. Everything else is the HTTP you already know:

  • Each endpoint — one method + path combination the API answers, like GET /weather/{city} — is a resource in the REST sense of lesson 4-3.
  • Requests and responses carry the same headers, status codes, and bodies from lessons 4-1 and 4-2.
  • The body format is almost always JSON, which deserves a proper introduction.

JSON, properly

JSON (JavaScript Object Notation) is a plain-text format for structured data. It won the API world because it is readable by humans, and because its shapes map directly onto the data structures every language already has:

{
  "city": "Lisbon",
  "temp_c": 21,
  "windy": false,
  "tags": ["sunny", "mild"]
}
  • { } is an object: key–value pairs (a dict in Python, an object in JavaScript).
  • [ ] is an array: an ordered list.
  • Values are strings (always in double quotes), numbers, true/false, null, or nested objects and arrays.

The strictness matters: single quotes, trailing commas, and Python-style True are all invalid JSON, and a server receiving them answers 400 Bad Request. When an API call fails with a 400, a malformed body is the first suspect.

Code exercise · python

Run this. json.loads parses a JSON text into Python data (loads = "load from string"). After parsing, the object is a dict and the array is a list — you use them like any other Python data. Note the JSON false became Python's False.

Quiz

Which of these is valid JSON?

Code exercise · python

Your turn, play the server. A request just asked for an order summary. Compute the total price of the orders, build a reply dict with keys "count" and "total", and print it as JSON with json.dumps (dumps = "dump to string") — the exact text that would become the response body.

Problem

Nearly every modern API sends and receives its data in one plain-text format built from objects, arrays, strings, and numbers. What is it called? (Four letters.)