What FastAPI Is: Starlette, Pydantic, uvicorn and What async def Really Gives You
FastAPI in one small Airport Board app: Starlette for the web side, Pydantic for the data, uvicorn as the server. Type hints turn gate=abc into a 422, the OpenAPI file and /docs page come for free, and async def only helps when something inside awaits.
What you will learn
- Name the two libraries FastAPI is built on and the server that runs it
- Use type hints and a Pydantic model so bad input gets a 422 before your code runs
- Read the OpenAPI description and the /docs page FastAPI writes for you
- Explain when async def helps and when it does nothing
Before you start
- Python functions and type hints
- Decorators in Python
Every API has jobs that have nothing to do with your actual idea. You check that a gate number really is a number. You write a page that explains your routes, and it goes out of date the day the code changes. You turn data into JSON and back, again and again. And while a request waits for a database, the worker handling it just sits there.
FastAPI's idea is simple: you describe your data once, with type hints, and it does that glue for you. We'll see what that means with one small app called Airport Board, in a single main.py, plus a check script that calls it.
What FastAPI is made of
FastAPI is a Python framework for building APIs, and it stands on two other libraries:
- Starlette handles the web side: routes, requests and responses.
- Pydantic handles the data side: checking values and turning them into JSON.
Your code sits on top. You write normal Python functions with type hints, and FastAPI connects them to the other two. Underneath it all is a server, uvicorn, which takes requests from the network and hands them to your app. The two talk through a standard called ASGI, the Asynchronous Server Gateway Interface.
Your first route
Here's the whole app, main.py:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(title="Airport Board")
class Flight(BaseModel):
code: str
gate: int
on_time: bool = True
@app.get("/")
async def home():
return {"message": "Welcome to the airport"}
@app.get("/flights/{code}")
async def get_flight(code: str, gate: int = 12) -> Flight:
return Flight(code=code, gate=gate)
app = FastAPI(title="Airport Board") makes the app. @app.get("/") is a decorator: when a GET request comes for the home path, call the function below. home returns a normal Python dictionary, and FastAPI turns it into JSON for you.
To call it without starting a server, check_app.py uses FastAPI's test client:
import json
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
resp = client.get("/")
print("GET / ->", resp.status_code)
print(resp.json())
GET / -> 200
{'message': 'Welcome to the airport'}
uvicorn serves the app
To serve it over the network, run uvicorn. main is the file and app is the object inside it:
uvicorn main:app --port 8765
INFO: Started server process [3636]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8765 (Press CTRL+C to quit)
INFO: 127.0.0.1:55264 - "GET / HTTP/1.1" 200 OK
A request comes in for /. uvicorn receives it and hands it to the app through ASGI. FastAPI finds the route and calls home. The dictionary goes back as JSON, and uvicorn sends the response and logs one line. The step-by-step install and first run are in FastAPI Hello World.
Declare the shape with Pydantic
Flight inherits from Pydantic's BaseModel. It has three fields: code is a string, gate is an int, and on_time is a bool that defaults to True. That's the shape of a flight, written once.
In get_flight, code is in the path (the curly braces), so it comes from the URL. gate isn't in the path, so FastAPI reads it from the query string, with 12 as the default. The arrow, -> Flight, says the function returns a Flight.
resp = client.get("/flights/AB123")
print("GET /flights/AB123 ->", resp.status_code)
print(resp.json())
resp = client.get("/flights/AB123?gate=7")
print("GET ...?gate=7 ->", resp.status_code)
print(resp.json())
GET /flights/AB123 -> 200
{'code': 'AB123', 'gate': 12, 'on_time': True}
GET ...?gate=7 -> 200
{'code': 'AB123', 'gate': 7, 'on_time': True}
With ?gate=7, the gate comes back as the number 7, not the text "7". The type hint did that conversion.
A wrong value never reaches your code
Now a bad boarding pass: gate=abc.
resp = client.get("/flights/AB123?gate=abc")
print("GET ...?gate=abc ->", resp.status_code)
print(json.dumps(resp.json(), indent=2))
GET ...?gate=abc -> 422
{
"detail": [
{
"type": "int_parsing",
"loc": [
"query",
"gate"
],
"msg": "Input should be a valid integer, unable to parse string as an integer",
"input": "abc"
}
]
}
FastAPI tried to turn abc into an int, couldn't, and answered 422 Unprocessable Entity. get_flight never ran. The body says what went wrong (int_parsing), where (query, then gate) and what you sent. You wrote zero checks for this. Path, query and body parameters get their own article: FastAPI Path, Query and Body Parameters.
OpenAPI, written for you
FastAPI reads your routes and models and writes a description of the whole API at /openapi.json. The rest of check_app.py reads it:
spec = client.get("/openapi.json").json()
print("openapi.json keys:", list(spec))
print("openapi:", spec["openapi"])
print("title:", spec["info"]["title"])
print("paths:", list(spec["paths"]))
print("schemas:", list(spec["components"]["schemas"]))
print(json.dumps(
spec["components"]["schemas"]["Flight"], indent=2
))
openapi.json keys: ['openapi', 'info', 'paths', 'components']
openapi: 3.1.0
title: Airport Board
paths: ['/', '/flights/{code}']
schemas: ['Flight', 'HTTPValidationError', 'ValidationError']
{
"properties": {
"code": {
"type": "string",
"title": "Code"
},
"gate": {
"type": "integer",
"title": "Gate"
},
"on_time": {
"type": "boolean",
"title": "On Time",
"default": true
}
},
"type": "object",
"required": [
"code",
"gate"
],
"title": "Flight"
}
Our title is there, both paths are there, and Flight lists code and gate as required, because only on_time has a default. The two validation schemas next to it are FastAPI's own, for the 422 error we just saw. OpenAPI is an open standard, so a front end, another team or an AI tool can read this one file and know how to call your API.
Interactive docs at /docs
docs = client.get("/docs")
print("GET /docs ->", docs.status_code)
print(docs.headers["content-type"])
print("Swagger page:", "swagger-ui" in docs.text)
GET /docs -> 200
text/html; charset=utf-8
Swagger page: True
/docs is a Swagger UI page. It reads openapi.json and draws every route as a row you can open, fill in and send. Because the page is built from the code, it changes when the code changes.
What async def really gives you
Both routes are async def. In FastAPI, one worker (the event loop) can look after many requests. When a request reaches an await, for example while it waits for another service, the worker switches to the next request, and comes back when the answer arrives.
The limit: async def only helps when the work inside actually awaits. If the code does something slow that doesn't await, a blocking call, the worker is stuck and every other request waits too. Our home waits for nothing, so here async changes nothing. If you write a plain def instead, FastAPI runs it on a separate thread, so a slow plain function doesn't hold up the others.
This matters as soon as a database is involved. You'll see it timed in FastAPI with SQLAlchemy Models and Alembic Migrations, and checked against the real blog in How a Request and a Login Flow Through the FastAPI Blog.
Why this helps when an AI agent writes the code
Type hints and models are a contract: they say what comes in and what goes out, so an AI coding agent has less to guess. A sample prompt in Role, Context, Task and Format:
You're a FastAPI developer.
main.pyhas a Flight model and two routes. Add a route that returns only a flight's code and on_time, with type hints. Show only the changed lines.
When the diff comes back, check three things. Does the new route have type hints? Does it use the model where it should? Does it show up in /docs?
Common mistakes
- Thinking FastAPI is the server. It's the app. uvicorn is the server, and the two talk over ASGI.
- Writing validation by hand. A type hint like
gate: intalready turnsabcaway with a 422. - Expecting
async defto make code fast. It only helps when the slow work inside is awaited. - Editing docs by hand.
/openapi.jsonand/docsare built from the code, so change the code instead.
Quick recap
| Piece | Job | In Airport Board |
|---|---|---|
| Starlette | routes, requests, responses | @app.get(...) |
| Pydantic | check data, build JSON | Flight, the 422 for gate=abc |
| uvicorn | the ASGI server | uvicorn main:app --port 8765 |
| OpenAPI | description of the API | /openapi.json, version 3.1.0 |
| Swagger UI | interactive docs | /docs |
async def | frees the worker at each await | no effect here, nothing awaits |
Try it yourself
Add a terminal field to Flight with a default value, run python check_app.py again, and find the new field in the Flight schema it prints.
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
FastAPI Hello World: Routes, uvicorn and the Free Swagger Page
The smallest FastAPI app: two routes in main.py, started with uvicorn. Follow one request from the browser to the route table and back as JSON, see a 404, and try the routes on the free Swagger page at /docs.
RESTful API Basics: Resources, Methods, Stateless Requests and Status Codes
An API is the waiter between your program and a server. REST gives each resource an address and uses the HTTP method for the action. Send GET, POST, PUT, PATCH and DELETE to a tiny local server with urllib, see why requests are stateless, and read 200, 201, 204, 400 and 404.
Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
One small project lists two blog posts three times: as a Django view, a Flask route and a FastAPI endpoint. See each shape with its real output, what each framework includes, and a three-question way to choose.
One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
The same blog built in Django, FastAPI and Flask, compared line by line: the list route, the Post model, the template loop, the project layout and the extras, with a ROSETTA map you can use to port a feature with AI.
