FastAPI has become one of the most popular ways to build APIs in Python, and it’s easy to see why. You write normal Python functions with type hints, and FastAPI gives you request validation, JSON serialisation, interactive documentation and excellent performance, with very little extra code.
In this tutorial, we’ll build a small but complete task management API with create, read, update and delete (CRUD) endpoints, validation, proper status codes and automated tests. Set a timer; 30 minutes is realistic.
Minute 0–5: Setup
Create a project folder and a virtual environment:
mkdir task-api && cd task-api
python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate
pip install "fastapi[standard]" pytest
The fastapi[standard] extra installs Uvicorn (the ASGI server) and other useful tools.
Minute 5–15: Write the API
Create main.py:
```python
from datetime import datetime
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field
app = FastAPI(title="Task API", version="1.0.0")
class TaskCreate(BaseModel):
title: str = Field(min_length=1, malength=200)
description: str | None = None
done: bool = False
class Task(TaskCreate):
id: int
created_at: datetime
# In-memory storage for this tutorial (use a database in real apps)
tasks: dict[int, Task] = {}
next_id = 1
@app.get("/tasks", response_model=list[Task])
def list_tasks(done: bool | None = None):
items = list(tasks.values())
if done is not None:
items = [t for t in items if t.done == done]
return items
@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
task = tasks.get(task_id)
if task is None:
raise HTTPException(status_code=404, detail="Task not found")
return task
@app.post("/tasks", response_model=Task, status_code=status.HTTP_201_CREATED)
def create_task(payload: TaskCreate):
global next_id
task = Task(id=next_id, created_at=datetime.now(), **payload.model_dump())
tasks[next_id] = task
next_id += 1
return task
@app.put("/tasks/{task_id}", response_model=Task)
def update_task(task_id: int, payload: TaskCreate):
if task_id not in tasks:
raise HTTPException(status_code=404, detail="Task not found")
updated = Task(id=task_id, created_at=tasks[task_id].created_at, **payload.model_dump())
tasks[task_id] = updated
return updated
@app.delete("/tasks/{task_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_task(task_id: int):
if tasks.pop(task_id, None) is None:
raise HTTPException(status_code=404, detail="Task not found")
### What's happening here
- **`TaskCreate`** describes what clients send. Pydantic validates it automatically: a missing or empty `title` is rejected with a clear error.
- **`Task`** extends it with server-generated fields (`id`, `created_at`).
- **`response_model`** controls exactly what the API returns, which is useful for hiding internal fields.
- **Path parameters** (`task_id: int`) are converted and validated. Calling `/tasks/abc` returns a validation error automatically.
- **Query parameters** (`done: bool | None = None`) become optional filters: `/tasks?done=true`.
- **`HTTPException`** returns proper error responses like 404.
## Minute 15–20: Run it and explore the docs
Start the development server:
```bash
fastapi dev main.py
(or uvicorn main:app --reload if you installed Uvicorn separately)
Now open:
- http://127.0.0.1:8000/docs: interactive Swagger UI, where you can try every endpoint
- http://127.0.0.1:8000/redoc: alternative ReDoc documentation
- http://127.0.0.1:8000/openapi.json: the generated OpenAPI specification
This automatic documentation is one of FastAPI’s biggest advantages. Front-end developers and API consumers can explore your API without asking you.
Try it with curl
curl -X POST http://127.0.0.1:8000/tasks \
-H "Content-Type: application/json" \
-d '{"title": "Write blog post", "description": "FastAPI tutorial"}'
curl http://127.0.0.1:8000/tasks
curl "http://127.0.0.1:8000/tasks?done=false"
Minute 20–25: See validation in action
Send an invalid request:
curl -X POST http://127.0.0.1:8000/tasks \
-H "Content-Type: application/json" \
-d '{"title": ""}'
FastAPI responds with HTTP 422 and a JSON body explaining exactly which field failed and why. You didn’t write any validation code; the Field(min_length=1) constraint did it.
Minute 25–30: Add tests
Create test_main.py:
```python
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_and_get_task():
r = client.post("/tasks", json={"title": "Write blog post"})
assert r.status_code == 201
task_id = r.json()["id"]
r = client.get(f"/tasks/{task_id}")
assert r.status_code == 200
assert r.json()["title"] == "Write blog post"
def test_missing_task_returns_404():
assert client.get("/tasks/9999").status_code == 404
def test_empty_title_rejected():
assert client.post("/tasks", json={"title": ""}).status_code == 422
Run:
```bash
pytest -q
You should see all three tests pass. FastAPI’s TestClient calls your API in-process, so tests are fast and need no running server.
Status codes used in this API
| Endpoint | Success | Errors |
|---|---|---|
GET /tasks | 200 | — |
GET /tasks/{id} | 200 | 404 not found, 422 invalid ID |
POST /tasks | 201 Created | 422 validation error |
PUT /tasks/{id} | 200 | 404, 422 |
DELETE /tasks/{id} | 204 No Content | 404 |
Using correct status codes makes your API predictable for clients.
Taking it further
The in-memory dictionary keeps the tutorial simple, but data disappears when the server restarts. For a real application:
1. Add a database
Use SQLAlchemy or SQLModel with PostgreSQL, MySQL or SQL Server. FastAPI’s dependency injection (Depends) is the standard way to provide a database session to each request.
2. Add authentication
Protect endpoints with OAuth2 and JWT tokens, or API keys for server-to-server use. FastAPI includes security utilities that integrate with the docs, so you can authorise requests directly from Swagger UI.
3. Organise with routers
As the API grows, split endpoints into modules using APIRouter:
from fastapi import APIRouter
router = APIRouter(prefix="/tasks", tags=["tasks"])
@router.get("/")
def list_tasks(): ...
Then include it in the main app with app.include_router(router).
4. Use async where it helps
FastAPI supports async def endpoints. Use them with async database drivers and HTTP clients for high-concurrency workloads. For simple CPU-light code with synchronous libraries, normal def functions are fine; FastAPI runs them in a thread pool.
5. Deploy
Common options:
- Uvicorn behind a reverse proxy such as Nginx or IIS
- Docker containers on a cloud platform
- Managed platforms that run ASGI applications
Use multiple worker processes in production and configure CORS if browsers call the API from another domain.
Common beginner mistakes
| Mistake | Fix |
|---|---|
Forgetting response_model | Explicitly define outputs to avoid leaking internal fields |
| Returning 200 for everything | Use 201, 204, 404 and 422 appropriately |
| Global mutable state in production | Use a database |
Blocking calls inside async def | Use async libraries, or plain def endpoints |
| No tests | Start with TestClient from day one |
What you have now
In 30 minutes, you’ve built a validated, documented and tested REST API. That’s the real strength of FastAPI: it removes boilerplate so you can focus on your business logic.
From here, add a database, authentication and routers, and you’ll have the foundation for a production-ready service.
Leave a Comment