FastAPI is a modern Python framework for building web APIs. You write normal Python functions with type hints, and FastAPI turns them into API endpoints that validate incoming data, return JSON, and generate interactive documentation automatically. It’s fast to learn, fast to run, and one of the most popular ways to build APIs in Python.
An API lets other programs use your data and logic: a mobile app, a website’s JavaScript, another company’s system, or your own scripts. If you’ve called APIs with requests, this is the other side: building one. FastAPI makes that surprisingly short, because the type hints you write do double duty as validation rules and documentation.
In this guide, you’ll build a small Projects API for a web design studio, with endpoints to create, list, update, and delete projects. Every command and response shown was run against the real app. If you’re deciding between frameworks, see Python Web Frameworks: Django vs Flask vs FastAPI.
Install FastAPI
In a new project folder, create a virtual environment, activate it, and install FastAPI with its standard extras, which include the Uvicorn server and the fastapi command:
python -m pip install "fastapi[standard]"
The Complete App
Save this as main.py. It’s about 60 lines, and each part is explained below:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
app = FastAPI(title="Projects API")
class ProjectIn(BaseModel):
client: str = Field(min_length=1)
name: str = Field(min_length=1)
budget: float = Field(gt=0)
status: str = "planned"
class Project(ProjectIn):
id: int
projects: dict[int, Project] = {}
next_id = 1
@app.get("/")
def home():
return {"message": "Projects API is running"}
@app.get("/projects")
def list_projects(status: str | None = None) -> list[Project]:
items = list(projects.values())
if status:
items = [p for p in items if p.status == status]
return items
@app.get("/projects/{project_id}")
def get_project(project_id: int) -> Project:
if project_id not in projects:
raise HTTPException(status_code=404, detail="Project not found")
return projects[project_id]
@app.post("/projects", status_code=201)
def create_project(data: ProjectIn) -> Project:
global next_id
project = Project(id=next_id, **data.model_dump())
projects[project.id] = project
next_id += 1
return project
@app.put("/projects/{project_id}")
def update_project(project_id: int, data: ProjectIn) -> Project:
if project_id not in projects:
raise HTTPException(status_code=404, detail="Project not found")
project = Project(id=project_id, **data.model_dump())
projects[project_id] = project
return project
@app.delete("/projects/{project_id}", status_code=204)
def delete_project(project_id: int):
if project_id not in projects:
raise HTTPException(status_code=404, detail="Project not found")
del projects[project_id]
Start it with the development server, which reloads automatically when you save changes:
fastapi dev main.py
Starting FastAPI in development mode
Server started at http://127.0.0.1:8000
Documentation at http://127.0.0.1:8000/docs
How It Works
Routes
app = FastAPI() creates the application. Each decorator connects a URL and an HTTP method to a function:
| Decorator | Request | Purpose |
|---|---|---|
@app.get("/projects") | GET /projects | List projects |
@app.get("/projects/{project_id}") | GET /projects/1 | Get one project |
@app.post("/projects") | POST /projects | Create a project |
@app.put("/projects/{project_id}") | PUT /projects/1 | Replace a project |
@app.delete("/projects/{project_id}") | DELETE /projects/1 | Delete a project |
Whatever the function returns (a dictionary, a list, or a model) is sent back as JSON.
Path and Query Parameters
- Path parameters come from the URL itself: in
/projects/{project_id}, the function receivesproject_id: int. Because of the type hint, FastAPI converts"1"to1and rejects/projects/abcwith a clear error. - Query parameters are function arguments that aren’t in the path:
status: str | None = Nonereads?status=activeand is optional because it has a default.
Validation With Pydantic Models
ProjectIn is a Pydantic model: a class that describes the data you expect. Field(min_length=1) and Field(gt=0) add rules, and status has a default. When a request arrives, FastAPI checks the JSON against the model before your function runs. Project extends it with an id for responses, and the -> Project return types tell FastAPI what to send back and document.
Errors
raise HTTPException(status_code=404, detail="Project not found") stops the function and returns a proper error response. Use 404 for missing items, 401 or 403 for permission problems, and 400 or 422 for bad input.
Try It With curl
Create two projects:
curl -X POST http://127.0.0.1:8000/projects \
-H "Content-Type: application/json" \
-d '{"client": "Bakery Lopez", "name": "New website", "budget": 2400}'
{"client":"Bakery Lopez","name":"New website","budget":2400.0,"status":"planned","id":1}
curl -X POST http://127.0.0.1:8000/projects \
-H "Content-Type: application/json" \
-d '{"client": "Garcia Law", "name": "SEO audit", "budget": 600, "status": "active"}'
{"client":"Garcia Law","name":"SEO audit","budget":600.0,"status":"active","id":2}
Notice the defaults and conversions: the first project got "status":"planned", and both budgets became decimals. Now filter with a query parameter:
curl "http://127.0.0.1:8000/projects?status=active"
[{"client":"Garcia Law","name":"SEO audit","budget":600.0,"status":"active","id":2}]
Ask for a project that doesn’t exist:
curl http://127.0.0.1:8000/projects/99
{"detail":"Project not found"}
And send invalid data, an empty client and a negative budget:
curl -X POST http://127.0.0.1:8000/projects \
-H "Content-Type: application/json" \
-d '{"client": "", "name": "Logo", "budget": -50}'
{"detail":[{"type":"string_too_short","loc":["body","client"],"msg":"String should have at least 1 character","input":"","ctx":{"min_length":1}},{"type":"greater_than","loc":["body","budget"],"msg":"Input should be greater than 0","input":-50,"ctx":{"gt":0.0}}]}
FastAPI rejected it with status 422 and a message for each problem, without a single line of validation code in your function. A DELETE request returns status 204 (No Content) when it succeeds.
Prefer Python to curl? The same calls work with requests: requests.post("http://127.0.0.1:8000/projects", json={...}).
Automatic Interactive Documentation
Open http://127.0.0.1:8000/docs in a browser. FastAPI builds an interactive page (Swagger UI) from your code, listing every endpoint, parameter, and model. Click an endpoint, choose Try it out, and send real requests from the browser. There’s a second style at /redoc, and the raw OpenAPI description at /openapi.json, which other tools can use to generate client code.
This documentation is always up to date, because it comes from the same type hints and models that run your API.
Protecting Endpoints With an API Key
FastAPI’s dependencies run before an endpoint and can stop the request. Here’s a simple API key check, reading the expected key from an environment variable:
import os
from fastapi import Depends, FastAPI, Header, HTTPException
app = FastAPI()
API_KEY = os.environ.get("PROJECTS_API_KEY", "change-me")
def require_api_key(x_api_key: str = Header()):
if x_api_key != API_KEY:
raise HTTPException(status_code=401, detail="Invalid API key")
@app.get("/reports/revenue", dependencies=[Depends(require_api_key)])
def revenue_report():
return {"month": "2026-11", "revenue": 4649.0}
A request without the X-API-Key header gets 422 (the header is required), a wrong key gets 401 Invalid API key, and the right key returns the report. For real users and logins, look into FastAPI’s OAuth2 support, and always serve APIs over HTTPS.
Testing Your API
FastAPI includes a TestClient, so you can test endpoints with pytest without starting a server. Save this as test_main.py:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_and_get_project():
response = client.post(
"/projects", json={"client": "Valley Fitness", "name": "Class schedule", "budget": 900}
)
assert response.status_code == 201
project_id = response.json()["id"]
response = client.get(f"/projects/{project_id}")
assert response.status_code == 200
assert response.json()["client"] == "Valley Fitness"
def test_missing_project_returns_404():
response = client.get("/projects/999")
assert response.status_code == 404
assert response.json() == {"detail": "Project not found"}
def test_budget_must_be_positive():
response = client.post("/projects", json={"client": "A", "name": "B", "budget": 0})
assert response.status_code == 422
python -m pytest -q
... [100%]
3 passed in 0.55s
From Practice to Production
The app keeps projects in a dictionary, so they disappear when the server restarts. For a real API:
- Use a database. SQLAlchemy works well with FastAPI, and the FastAPI team’s SQLModel library combines SQLAlchemy and Pydantic models in one class.
- Run it with
fastapi run main.py(production mode, no auto-reload), usually in a Docker container, behind a reverse proxy that handles HTTPS. - Keep secrets in environment variables, as with the API key above, and see The Importance of the .env File in Python Projects.
- Add async where it helps. Endpoints can be
async defwhen they call other async libraries, likehttpx. Plaindefendpoints, as in this guide, are perfectly fine and run in a thread pool.
FastAPI vs. Flask
| FastAPI | Flask | |
|---|---|---|
| Best for | APIs | Websites and APIs |
| Validation | Built in, from type hints | Add-on libraries |
| Documentation | Automatic (Swagger UI and ReDoc) | Add-on libraries |
| Async | Built in | Supported, less central |
| Templates for HTML pages | Possible, not the focus | A core feature |
For an API, FastAPI saves a lot of code. For a traditional website with HTML pages, see the Flask guide.
Common Mistakes to Avoid
- Missing type hints. FastAPI relies on them; without them, you lose validation and documentation.
- Using
fastapi devin production. It’s for development. Usefastapi run(or Uvicorn directly) with a process manager or container. - Storing data in memory. It’s fine for learning, but it’s lost on restart and not shared between workers. Use a database.
- Returning the wrong status codes. Use
201for created,204for deleted,404for missing, and422or400for bad input, so clients can react correctly. - Leaving endpoints open. Anything that changes data should require authentication.
Frequently Asked Questions
Is FastAPI good for beginners?
Yes, if you know Python functions and dictionaries. Type hints may be new, but FastAPI uses them in a simple way; see Python Type Hints for a quick introduction.
Is FastAPI really fast?
It’s one of the fastest Python frameworks, thanks to the Starlette toolkit and async support underneath. “Fast” also refers to development speed: validation and documentation come for free.
Do I need to know async to use FastAPI?
No. Regular def functions work well. Use async def only when your code awaits other async operations.
Can FastAPI serve HTML pages?
Yes, with Jinja2 templates or static files, but it’s designed for APIs. Many projects pair a FastAPI backend with a separate JavaScript frontend.
Conclusion
FastAPI turns plain Python functions with type hints into a complete API: routes from decorators, validation from Pydantic models, clear error responses, and interactive documentation at /docs, all with very little code. Start with fastapi dev, test every endpoint with curl or the docs page and with TestClient, then add a database, authentication, and HTTPS on the way to production.
