Skip to content
skillbld
Building APIs with FastAPI · 12-day planAll days
Day 1 of 12 25 min

Find out what a web API is and how HTTP requests and responses work - methods, paths, status codes and JSON. Then write your first FastAPI app, call it from code, and meet the interactive documentation FastAPI writes for you.

By the end of today you can

  • Explain what a web API is and why apps use them
  • Name the parts of an HTTP request and response
  • Use the common methods (GET, POST, PUT, PATCH, DELETE) and status codes
  • Write a FastAPI app with path operations that return JSON
  • Call an app with TestClient and find its automatic documentation

Every app you use talks to servers. When a weather app shows tomorrow's forecast, it has asked a server's API for data and got an answer back. Over this course you'll build APIs of your own with FastAPI, one of the most popular Python frameworks, used by companies like Microsoft, Netflix and Uber.

Mind map · click a dot to fold, drag to pan

Requests and responses

Sketch
An HTTP request and response. A client, such as a phone app, sends a request to a server: the method GET, the path /books/42, headers like Accept: application/json, and for some methods a body. The server, a FastAPI app, finds the function for that method and path, runs it, and sends back a response: a status code such as 200 OK, headers like Content-Type: application/json, and a body of JSON data, such as the book's id, title and price.

An API conversation is always a request and a response:

PartExample
Method: what to doGET
Path: which thing/books/42
Query: options?currency=EUR
Headers: extra informationAuthorization: Bearer …
Body: data sent (for POST, PUT…){"title": "Dune"}
Status code: how it went200 OK
Response body: the data back{"id": 42, "title": "Dune"}

Methods

MethodMeansExample
GETReadGet book 42
POSTCreateAdd a new book
PUTReplaceReplace book 42 entirely
PATCHUpdate partChange book 42's price
DELETERemoveDelete book 42

Status codes

CodeMeans
200 OKIt worked, here's the data
201 CreatedA new thing was created
204 No ContentIt worked, nothing to send back
400, 422Your request was wrong or invalid
401, 403Not logged in / not allowed
404 Not FoundThat thing doesn't exist
500The server broke

JSON is the usual format: text that looks like Python dicts and lists, {"title": "Dune", "tags": ["sci-fi"]}, readable by every programming language.

Your first FastAPI app

Press Run. The first run downloads FastAPI into your browser, which takes a few seconds:

main.py · editable
Output
Press Run to execute this code.
Sketch
The parts of a FastAPI path operation. app = FastAPI() creates the application. The decorator @app.get with the path /books registers the function underneath for GET requests to /books. The function, list_books, runs when such a request arrives. Whatever it returns, like a list of dicts, FastAPI converts to JSON and sends back with status 200.
  • app = FastAPI() creates the application.
  • @app.get("/books") is a path operation decorator: it says "call this function for GET requests to /books". There's also @app.post, @app.put, @app.patch and @app.delete.
  • The function returns ordinary Python data: dicts, lists, strings, numbers. FastAPI turns it into JSON.
  • A path nobody handles gets 404 automatically.

Try adding your own endpoint, such as @app.get("/about"), and a request to it.

What's TestClient?

Normally a client is a browser, a phone app or another server, sending real HTTP requests over the network. TestClient sends requests straight to your app inside the same program: perfect for trying things out and for automated tests (Day 10). In this course it's how you'll call your APIs in the page.

Running it for real

On your own computer, install FastAPI and run the app with its development server:

pip install "fastapi[standard]"
fastapi dev main.py

The server starts at http://127.0.0.1:8000. Visit /books in your browser to see the JSON, and /docs for something special.

Free documentation

Sketch
FastAPI's automatic documentation at /docs. Each endpoint is listed by method and path, colour coded: GET /books in blue, POST /books in green, DELETE /books/{book_id} in red. Opening one shows its parameters, the request body it expects and example responses, with a Try it out button that sends a real request. It's generated from your code through the OpenAPI standard, so it never goes out of date.

FastAPI reads your code (paths, parameters, types) and generates an OpenAPI description of your API. From that it builds interactive documentation at /docs (Swagger UI) and /redoc, where anyone can read and try every endpoint. When you change the code, the docs change with it.

You can peek at the description from code:

main.py · editable
Output
Press Run to execute this code.

Recap

  • An API lets programs exchange data over HTTP: a request (method, path, headers, body) gets a response (status code, headers, body), usually JSON.
  • Methods: GET read, POST create, PUT/PATCH update, DELETE remove. Status codes: 2xx ok, 4xx client error, 5xx server error.
  • FastAPI: app = FastAPI() and @app.get("/path") on a function that returns data.
  • TestClient(app) sends requests in code; /docs documents and tests your API in the browser.

Tomorrow: reading values from the URL with path and query parameters.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    What does a web API do?

  2. 2

    Which HTTP method is used to read data without changing anything?

  3. 3

    What does the status code 404 mean?

  4. 4

    In FastAPI, what does @app.get("/hello") do?

  5. 5

    Where can you see and try every endpoint of a running FastAPI app?

Was this lesson helpful?

Need a breather? Take a two-minute break

Keep going