Building an API with FastAPI
What is FastAPI?
Section titled “What is FastAPI?”If you come from the Node.js world you already know the pattern: a lightweight framework that maps HTTP verbs and URL paths to handler functions, handles request parsing, and returns JSON responses. FastAPI does exactly that for Python — but with a few superpowers baked in from the start.
FastAPI is built on two libraries you will get to know well:
- Starlette — an ASGI web toolkit (the async equivalent of Node’s
httpmodule). - Pydantic — a data-validation library powered by Python type hints (think Zod + class-transformer rolled into one).
The result is a framework that generates OpenAPI docs automatically, validates request bodies and query parameters with zero boilerplate, and runs fully async by default.
FastAPI vs Express vs NestJS
Section titled “FastAPI vs Express vs NestJS”// Express — manual everythingconst express = require('express');const app = express();app.use(express.json());
app.get('/items/:id', (req, res) => { const id = Number(req.params.id); // manual cast if (isNaN(id)) return res.status(422).json({ error: 'bad id' }); res.json({ id, name: 'Widget' });});
app.listen(3000);
// NestJS — decorators + DI, similar concept// @Get(':id') findOne(@Param('id') id: string) { ... }# FastAPI — types do the workfrom fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")async def get_item(item_id: int): # int cast + 422 on failure — automatic return {"id": item_id, "name": "Widget"}
# Run with:# uvicorn main:app --reload# Docs at: http://localhost:8000/docsKey differences at a glance:
| Feature | Express | NestJS | FastAPI |
|---|---|---|---|
| Type safety | Manual / TS compiler | TS + class-validator | Python type hints |
| Validation | Manual / Joi / Zod | class-validator | Pydantic (automatic) |
| Async model | Callbacks / Promises | Promises / Observables | async/await (ASGI) |
| OpenAPI docs | swagger-jsdoc | @nestjs/swagger | Built-in, automatic |
| DI container | None built-in | Yes (IoC) | Depends() (lightweight) |
| Performance | Fast | Moderate | Very fast (Starlette) |
What you will build
Section titled “What you will build”Throughout this module you will construct a small Items API — the same kind of CRUD service you have probably built a dozen times in Node. Along the way you will cover:
- Project layout and startup
- Routing, path params, and query params
- Pydantic models for request / response schemas
- Automatic validation and constraints
- Response models and status codes
- Dependency injection with
Depends - Middleware and CORS
- Error handling with
HTTPException - Database integration with SQLAlchemy
- Testing with
TestClient+ pytest
Run this locally — needs FastAPI + a server. Install the stack:
pip install fastapi uvicorn[standard] pydantic sqlalchemy pytest httpx