You write eleven lines of Python. You run one command. And suddenly you have a working API, input checking, clear error messages and a documentation page you never wrote.
That's FastAPI. FastAPI is a Python framework for building APIs, where your type hints do the boring work: reading the request, checking the data, and writing the docs.
But "it just works" is not a great feeling when something breaks. So let's follow one request, stop by stop, from the moment you press Enter to the moment JSON comes back.
The 11 lines
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Book(BaseModel):
title: str
pages: int
@app.post("/books")
def add_book(book: Book):
return {"saved": book.title, "pages": book.pages}
Run it:
pip install "fastapi[standard]"
fastapi dev main.py
Now open http://127.0.0.1:8000/docs. There's a full, clickable docs page for your API. You didn't write it. Keep that in mind, we'll see where it comes from.
Follow one request
Someone sends this:
POST /books
Content-Type: application/json
{"title": "Dune", "pages": "412"}
Notice "412" is a string, not a number. Watch what happens to it.
Stop 1: Uvicorn, the doorman
Your code doesn't listen on a port. Uvicorn does. It's a server program that sits on port 8000, receives raw bytes from the network, and turns them into a neat Python dictionary describing the request (method, path, headers). That format is called ASGI.
Think of Uvicorn as the doorman. It doesn't care what's inside the parcel. It just accepts it and passes it in.
Stop 2: Routing, the sorting desk
Inside FastAPI, a router looks at two things: the method (POST) and the path (/books). It finds the one function that matches, add_book.
No match? You get a 404 (wrong path) or 405 (right path, wrong method), and your code never runs.
Stop 3: Pydantic, the security check
This is the clever part. FastAPI looks at your function signature:
def add_book(book: Book):
It sees book: Book, so it knows the body must look like a Book. It hands the JSON to Pydantic, which checks every field:
-
title→"Dune"is a string. ✅ -
pages→"412"is a string, but it looks like a number, so Pydantic converts it to412. ✅
Now send something broken:
{"title": "Dune", "pages": "lots"}
Pydantic stops the request right here. Your function never runs. The client gets a 422 with a precise reason:
{
"detail": [{
"type": "int_parsing",
"loc": ["body", "pages"],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "lots"
}]
}
Look at loc: it tells the caller exactly which field was wrong. You wrote zero if statements for this.
💡 This is lesson one of the FastAPI course on DevTrail. You can break requests like this yourself and watch the 422s, right in your browser, with nothing to install.
Stop 4: Your function, finally
By the time add_book runs, book is a real Python object. book.pages is the integer 412, not a string. You can trust your data, so your function stays short and only does the actual work.
Stop 5: Back out as JSON
You return a plain dict. FastAPI turns it into JSON, adds the right headers and a 200 status, and Uvicorn sends the bytes back to the client.
The whole trip in one line:
bytes → Uvicorn → ASGI dict → router → Pydantic check → your function → JSON → bytes
So where did the docs come from?
Same place as the validation: your type hints. FastAPI already knows the path, the method, and the exact shape of Book. It writes that down in a standard format called OpenAPI, and /docs simply draws a page from it.
One source of truth (your types) gives you three things: conversion, validation and documentation. That's the whole idea behind FastAPI.
The mistake almost everyone makes: async everywhere
FastAPI supports async def, so it's tempting to write it everywhere:
import time
@app.get("/slow")
async def slow():
time.sleep(5) # 🚨 blocks the whole server
return {"done": True}
async functions all share one event loop. time.sleep (or requests.get, or a normal database driver) freezes that loop, so every other request waits too.
The simple rule:
| Your code calls... | Write |
|---|---|
Normal blocking libraries (requests, time.sleep, most DB drivers) |
def (FastAPI runs it in a thread pool for you) |
Async libraries you await (httpx.AsyncClient, asyncpg) |
async def |
Plain def is not slower or "old fashioned" in FastAPI. It's often the safe choice.
FastAPI, Flask or Django?
| FastAPI | Flask | Django | |
|---|---|---|---|
| Best for | APIs, microservices, ML model serving | Small apps, quick prototypes | Full websites with admin, auth, ORM |
| Validation | Built in (Pydantic) | Add a library | Forms / DRF serializers |
| Auto docs | Yes, /docs
|
Add a library | With DRF + extra package |
| Async | Native | Partial | Partial |
| Learning curve | Low if you know type hints | Lowest | Higher, but batteries included |
If you're building an API in Python today, FastAPI is a very safe default.
What you'd learn next
You now understand one request, start to finish. A real backend needs a lot more:
- ✅ How a request flows through FastAPI (this post)
- 🔒 Path and query parameters, and how they're validated
- 🔒 Request bodies with nested Pydantic models
- 🔒 Response models and status codes (hiding passwords from responses)
- 🔒 Dependency injection, the feature that makes FastAPI apps clean
- 🔒 A real PostgreSQL database with SQLAlchemy
- 🔒 Login with JWT, password hashing, protected routes
- 🔒 Testing, background tasks, middleware
- 🔒 Deploying with Docker
- 🔒 Full projects you can put on your CV
🚀 Go from zero to hero with FastAPI
This post covered step 1 of 11. The full Learn FastAPI from Basic to Advanced course on DevTrail takes you through all of it: 11 modules and 49 hands-on lessons, ending with real projects.
Every lesson has code you run and check right in your browser. No setup, no "works on my machine".
Module 1 is free. Start the FastAPI course →

Top comments (0)