Skip to content

Building an API with 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 http module).
  • 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.

TypeScript
// Express — manual everything
const 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) { ... }
Python
# FastAPI — types do the work
from 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/docs

Key differences at a glance:

FeatureExpressNestJSFastAPI
Type safetyManual / TS compilerTS + class-validatorPython type hints
ValidationManual / Joi / Zodclass-validatorPydantic (automatic)
Async modelCallbacks / PromisesPromises / Observablesasync/await (ASGI)
OpenAPI docsswagger-jsdoc@nestjs/swaggerBuilt-in, automatic
DI containerNone built-inYes (IoC)Depends() (lightweight)
PerformanceFastModerateVery fast (Starlette)

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:

  1. Project layout and startup
  2. Routing, path params, and query params
  3. Pydantic models for request / response schemas
  4. Automatic validation and constraints
  5. Response models and status codes
  6. Dependency injection with Depends
  7. Middleware and CORS
  8. Error handling with HTTPException
  9. Database integration with SQLAlchemy
  10. Testing with TestClient + pytest

Run this locally — needs FastAPI + a server. Install the stack: pip install fastapi uvicorn[standard] pydantic sqlalchemy pytest httpx

Which library provides automatic request validation in FastAPI?
What is the FastAPI equivalent of `app.listen(3000)` in Express?
FastAPI generates OpenAPI (Swagger) docs automatically. Where are they served by default?