⚡ FastAPI from Scratch
FastAPI is the fastest Python framework for building modern APIs. With native type hints, automatic validation, and async performance, you can go from zero to a working API in minutes. Ask Claude Code: "cria uma FastAPI com endpoint de health check".
from fastapi import FastAPI
app = FastAPI(title="Minha API", version="0.1.0")
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
# Rodar: uvicorn main:app --reload
In one sentence: FastAPI + uvicorn = a live API in 5 lines of code.
📐 Pydantic Models
Pydantic turns Python classes into automatically validated schemas. If the client sends invalid data, FastAPI returns 422 with the exact error. Claude Code generates perfect Pydantic models from JSON examples.
from pydantic import BaseModel, Field
class ItemCreate(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0)
tags: list[str] = []
class ItemResponse(ItemCreate):
id: int
In one sentence: Pydantic automatically validates data; bad data never reaches your code.
🔁 CRUD Endpoints
Create, Read, Update, Delete. Every API starts with CRUD. FastAPI maps each operation to an HTTP verb: POST to create, GET to read, PUT to update, DELETE to remove. Claude Code generates a complete CRUD API in one prompt: "cria CRUD de items com FastAPI".
In one sentence: POST/GET/PUT/DELETE = the four operations every API needs.
🔒 Middleware and Auth
Middleware intercepts requests before they reach the endpoints. CORS, rate limiting, and authentication live here. FastAPI uses Depends() for dependency injection: create an auth function and inject it into any route.
Never do this
A public API with no auth, no CORS configured, and no rate limiting is an invitation to abuse.
In one sentence: Depends() + middleware = security on every request without repeating code.
📄 Automatic Docs (Swagger)
FastAPI automatically generates interactive documentation at /docs (Swagger UI) and /redoc (ReDoc). Each endpoint, model, and parameter is documented. You can test the API directly in the browser without Postman.
In one sentence: /docs = living documentation that updates itself with the code.
🌍 Local and Remote Deploy
Local: uvicorn main:app --reload. Production: gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker. For remote deployment, package it with Docker (next module) and send it to Railway, Fly.io, or any VPS with a reverse proxy (nginx/Caddy).
# Dev uvicorn main:app --reload --port 8000 # Producao gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
In one sentence: uvicorn for dev, gunicorn for production, Docker for deploy.
🧾 Module Summary
Next module:
5.4 — Automated Testing: pytest, TDD, and coverage.