APIs with FastAPI · Chapter 1 of 26
Your first API
By the end of this chapter you can say what an API is and what an HTTP request and response carry, write a FastAPI app with routes that answer JSON, run it with uvicorn and ask it with curl, read the documentation FastAPI writes for you, and call your app from a test. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: First API
- 4 tasks
- FastAPI
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
DakiyaGo picks parcels up from Jaipur's small businesses (blue pottery, block prints, spices, silver) and delivers them to pincodes across India. Today every booking comes in on WhatsApp: "2 parcels, 1.2 kg each, Mumbai 400076, COD 799". Imran, who looks after the merchants, types each one into a spreadsheet. Devika, the founder, has a bigger problem: the larger merchants run their own shop software, and their developers keep asking the same thing. "Where is your API? Our software should book the parcel when the order is placed, and ask you for the price before the customer pays."
Everything you have written in Python so far runs for you: you start it, it reads a file, prints, and stops. A merchant's software cannot use that. It needs a program of DakiyaGo's that is always running, that another program can reach over the network at any moment, ask a question in an agreed format, and get an answer it can read without a human. That program is an API. Aman, DakiyaGo's staff backend engineer, builds it with FastAPI, and this lab builds it with you, from the first route to a production service.
The lesson
An API is a program other programs call
An API (application programming interface) is a program that answers other programs. A web API answers over HTTP, the same protocol your browser speaks. Every exchange is one request and one response, both plain text on a network connection.
The request says what the client wants. This is the request curl sent to an API we will write in a moment (curl -v shows it, the lines starting with >):
> GET /hubs HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.88.1
> Accept: */*
- The method (
GET) says what kind of thing to do:GETreads,POSTcreates,PUTandPATCHchange,DELETEremoves. - The path (
/hubs) says which thing. One API has many paths. - Headers are
name: valuelines about the request: which host, which program asked, what it accepts. A request that sends data (a booking, say) adds a body after the headers.
The response says what happened, and carries the answer:
HTTP/1.1 200 OK
date: Thu, 22 Oct 2026 11:38:54 GMT
server: uvicorn
content-length: 108
content-type: application/json
[{"code":"JPR-MN","area":"Malviya Nagar","riders":14},{"code":"JPR-VK","area":"Vaishali Nagar","riders":11}]
The first line is the status: a number for programs and a phrase for people. Then headers (content-type: application/json says the body is JSON), a blank line, and the body. A merchant's software reads the status first, then parses the body. The status numbers come in families:
| Status | Means | For example |
|---|---|---|
| 2xx | it worked | 200 OK, 201 Created |
| 4xx | the client asked wrongly | 404 Not Found, 405 Method Not Allowed, 422 bad data |
| 5xx | the server failed | 500 Internal Server Error |
JSON is the language of the body: objects in {}, lists in [], strings in double quotes, numbers, true, false and null. It maps straight onto Python's dictionaries, lists, strings, numbers, True, False and None, which is why Python is pleasant for APIs.
A FastAPI app
FastAPI turns Python functions into HTTP routes. Here is that API, in hubs.py:
from fastapi import FastAPI
HUBS = [
{"code": "JPR-MN", "area": "Malviya Nagar", "riders": 14},
{"code": "JPR-VK", "area": "Vaishali Nagar", "riders": 11},
]
app = FastAPI()
@app.get("/hubs")
def hubs():
return HUBS
app = FastAPI()makes the application: one object that holds every route. It lives at the top level of the file, in a variable, so a server can find it.@app.get("/hubs")is a decorator: it registers the function below it as the answer toGET /hubs. The method is in the decorator's name (get,post,put,delete), the path is its argument.- The function's return value is the response. FastAPI turns the list into JSON, sets
content-type: application/jsonand the status 200. You never write JSON text yourself.
Running it, and asking it
An app does nothing until a server runs it. uvicorn is the server: it listens on a port, reads each request off the network, hands it to FastAPI, and writes the response back. You tell it the file and the variable, module:variable:
$ uvicorn hubs:app
INFO: Started server process [104]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
It keeps running, waiting for requests, until you press Ctrl+C. The lab has one terminal, so start it in the background with &, ask it with curl, and stop it with kill %1 (the first background job):
uvicorn hubs:app &
curl -i localhost:8000/hubs
kill %1
curl -i prints the status line and headers before the body, as above (from here on the date, server and length headers are left out). Ask for something the API does not have, and FastAPI answers for you:
$ curl -i localhost:8000/hub
HTTP/1.1 404 Not Found
content-type: application/json
{"detail":"Not Found"}
$ curl -i -X POST localhost:8000/hubs
HTTP/1.1 405 Method Not Allowed
allow: GET
content-type: application/json
{"detail":"Method Not Allowed"}
FastAPI picks a route by method and path together. /hub matches no path, so 404. /hubs exists, but only for GET, so a POST gets 405 and an allow header listing what would work.
On your own laptop you would use fastapi dev hubs.py instead: the same uvicorn underneath, but it restarts when you save the file, and prints where the docs are:
⚡️ Starting FastAPI in development mode
🐍 Using import string: hubs:app
🌐 Server started at http://127.0.0.1:8000
Documentation at http://127.0.0.1:8000/docs
Load once, answer many
The file runs once, when uvicorn imports it. Each route's function runs once per request. Add two prints and watch the log (uvicorn also logs every request it answered):
print("Loading the hubs")
HUBS = [{"code": "JPR-MN", "area": "Malviya Nagar", "riders": 14}]
app = FastAPI()
@app.get("/hubs")
def hubs():
print("Answering GET /hubs")
return HUBS
Loading the hubs
INFO: Started server process [104]
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
Answering GET /hubs
INFO: 127.0.0.1:42052 - "GET /hubs HTTP/1.1" 200 OK
Answering GET /hubs
INFO: 127.0.0.1:42062 - "GET /hubs HTTP/1.1" 200 OK
So work that is the same for every request (reading a file that changes once a month, building a lookup table) goes at the top of the file, and the route only answers from memory. Reading the file inside the route would open it on every request, all day, for the same answer.
JSON is not a string you write
A common first mistake is to turn the data into JSON text yourself:
@app.get("/hubs")
def hubs():
return json.dumps(HUBS)
HTTP/1.1 200 OK
content-type: application/json
"[{\"code\": \"JPR-MN\", \"area\": \"Malviya Nagar\", \"riders\": 14}]"
json.dumps made a string, and FastAPI did its job: it turned that string into JSON, which is a quoted string full of escaped quotes. The merchant's software asks for a list of hubs and gets one long string. Return the Python data and let FastAPI encode it.
The docs FastAPI writes for you
FastAPI reads your routes and writes a description of the whole API in a standard format, OpenAPI, at /openapi.json:
$ curl -s localhost:8000/openapi.json
{"openapi":"3.1.0","info":{"title":"FastAPI","version":"0.1.0"},"paths":{"/hubs":{"get":{"summary":"Hubs","operationId":"hubs_hubs_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}}}}
/docs turns that document into a page where a developer can read every route and try it (open it in your browser on your own laptop; the page loads its scripts from the internet, which the lab does not have). Tools read /openapi.json too, to generate client code in other languages. The defaults say little: the title is FastAPI, the summary is made from the function's name, and routes without a tag sit under "default". You can name the API where you make the app, and describe each route in its decorator.
Calling your app from a test
You do not need a server to try an app. FastAPI's TestClient calls it directly, in the same Python process, exactly as an HTTP client would:
>>> from fastapi.testclient import TestClient
>>> from hubs import app
>>> client = TestClient(app)
>>> r = client.get("/hubs")
>>> r.status_code
200
>>> r.headers["content-type"]
'application/json'
>>> r.json()[0]
{'code': 'JPR-MN', 'area': 'Malviya Nagar', 'riders': 14}
>>> client.get("/riders").status_code
404
This is how your Check works: it imports your file, takes app, and calls your routes with a TestClient (task 1's check runs uvicorn for real instead). It is also how you will test your own APIs later in this lab.
Your turn
Four tasks, one app per file. Task 1 is the health route every API has; run it for real with uvicorn and curl before you press Check. Tasks 2 and 3 read DakiyaGo's data once and answer from memory: watch for answering a JSON string, and keep pincodes as strings. Task 4 is an interview question: be ready to say where /docs and /openapi.json come from, and why a merchant's developer cares.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
health.py: is the API up?
Merchants' software needs to know DakiyaGo's API is running. Make a FastAPI app in a variable called app with one route: GET /health answers the JSON object {"status": "ok"} with status 200.
Try it in the terminal: start it in the background with uvicorn health:app &, ask it with curl -i localhost:8000/health, and stop it with kill %1. The check runs your file with uvicorn the same way and asks GET /health over HTTP.
- Task 2
rates.py: the rate card
Merchants want DakiyaGo's prices in their own checkout. Make an app with one route: GET /rates answers the whole rate card from /workspace/data/rate_card.json, exactly as the file holds it.
Read the file once, when the app starts (at the top of the file), not on every request. The check calls GET /rates and compares the answer with the file, then makes every file read fail and calls it again: it must still answer.
- Task 3
serviceable.py: where DakiyaGo delivers
Merchants want the list of pincodes DakiyaGo serves before they offer delivery. /workspace/data/pincodes.json holds every pincode DakiyaGo knows; the ones it serves now have active set to true.
Make an app with one route: GET /serviceable answers an object with exactly two keys: count, how many pincodes are listed, and pincodes, the active pincodes as strings, smallest first. Every active pincode, each once, and no others.
- Task 4 · interview question
Interview: docs.py, an API that describes itself
Imran sends merchants' developers to /docs, the page FastAPI makes from your code. Make an app whose OpenAPI document (/openapi.json) has the title DakiyaGo API and the version 0.1.0, with one route: GET /health answering {"status": "ok"} as in task 1, with the summary Is the API up? and one tag, ops.
The check reads /openapi.json and opens /docs. The interviewer will ask where /docs and /openapi.json come from, and why a merchant's developer cares.
What you will learn
- What an API is, and what an HTTP request and response carry.
- A FastAPI app: routes, and functions whose return value becomes JSON.
- Running it: uvicorn, fastapi dev, and asking it with curl.
- Load once, answer many: what runs at startup and what runs per request.
- The docs FastAPI writes, and TestClient, which calls your app from a test.
More in First API
Build "Your first API" yourself
DakiyaGo, a Jaipur courier startup, takes bookings on WhatsApp. Merchants want an API, and you build it. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.