FastAPI Introduction
FastAPI is a modern, high-performance Python web framework for building APIs. It is built on top of Starlette (for the web/ASGI layer) and Pydantic (for data validation), and it uses native Python type hints to generate validation, documentation, and serialization automatically.
Why FastAPI?
- Speed: comparable to Go and Node.js; one of the fastest Python frameworks available.
- Less code: fewer bugs by removing whole categories of repetitive boilerplate.
- Fewer errors: automatic request validation via Pydantic with clear error messages.
- Automatic interactive docs: OpenAPI (Swagger UI) and ReDoc are generated for free.
- Type hints: full IDE autocompletion, static analysis, and mypy support.
- Async: first-class support for async def endpoints with modern libraries.
A Minimal API
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello world"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
Run it with Uvicorn:
uvicorn main:app --reload
Then open http://127.0.0.1:8000/docs to get interactive documentation generated from your code.
How It Works
FastAPI inspects the function signature of each route. Type hints like item_id: int become validation (422 with a clear error if the value is not an integer), default values become optional query parameters, and Pydantic models in the signature become request body validation.
Summary
FastAPI builds APIs from plain Python functions with type hints. It validates input automatically, generates interactive OpenAPI docs, and runs as an ASGI application on Uvicorn. The core loop: define route functions with typed parameters, start uvicorn, and use /docs to test your API in the browser.