FastAPI/
Lesson

Python has had web frameworks for over two decades. Django shipped in 2005, Flask in 2010. Both are battle-tested and power thousands of production applications. So why did Sebastian Ramirez create yet another framework in 2018? Because the Python ecosystem had a gap: there was no framework that combined modern async support, automatic data validation, and self-documenting APIs without requiring a mountain of boilerplateWhat is boilerplate?Repetitive, standardized code that follows a known pattern and appears in nearly every project - like setting up a server or wiring up database connections.. FastAPI fills that gap.

The ASGI revolution

To understand why FastAPI exists, you need to understand the shift from WSGI to ASGI.

WSGI (Web Server Gateway Interface) has been the standard for Python web apps since 2003. It works synchronously: one request comes in, the server processes it, sends the response, then moves to the next request. This is fine for traditional web pages, but it falls apart when you need to handle WebSockets, long-pollingWhat is polling?Repeatedly asking a server at regular intervals if anything has changed, which works but wastes resources when nothing is new., or thousands of concurrent connections.

ASGI (Asynchronous Server Gateway Interface) is the async successor. It lets your application handle multiple requests concurrently using Python's async/await syntax. A single process can juggle thousands of connections without blocking.

# WSGI style (Flask) - synchronous, one request at a time per worker
@app.route("/users")
def get_users():
    users = db.query("SELECT * FROM users")  # blocks until done
    return jsonify(users)

# ASGI style (FastAPI) - async, can handle other requests while waiting
@app.get("/users")
async def get_users():
    users = await db.query("SELECT * FROM users")  # yields control while waiting
    return users

The await keyword is the key difference. While the WSGI version blocks the entire worker process during the database query, the ASGI version yields control back to the event loopWhat is event loop?The mechanism that lets Node.js handle many operations on a single thread by delegating slow tasks and processing their results when ready., which can serve other requests in the meantime.

AI pitfall
AI sometimes generates FastAPI code that mixes WSGI-era patterns with ASGI, for example, using flask.jsonify() inside a FastAPI endpoint or importing from werkzeug. If you see Flask imports in FastAPI code, the AI is confusing frameworks.
02

Built on giants: Starlette and Pydantic

FastAPI is not built from scratch. It is a high-level layer on top of two well-established libraries.

Starlette: the HTTPWhat is http?The protocol browsers and servers use to exchange web pages, API data, and other resources, defining how requests and responses are formatted. engine

Starlette is a lightweight ASGI framework that handles all the low-level HTTP work: routing, middlewareWhat is middleware?A function that runs between receiving a request and sending a response. It can check authentication, log data, or modify the request before your main code sees it., WebSocket connections, static files, and background tasks. FastAPI delegates all of this to Starlette. When you define a route in FastAPI, Starlette is what actually receives the HTTP request and sends the response.

You rarely interact with Starlette directly when using FastAPI, but knowing it is there helps when debugging. Error tracebacks often include Starlette frames, and advanced configuration (custom middleware, lifespan events) uses Starlette APIs.

Pydantic: the validation engine

Pydantic is a data validation library that uses Python type hints to define and validate data schemas. FastAPI uses Pydantic models for request body parsing, response serializationWhat is serialization?Converting data from a program's internal format into a string or byte sequence that can be stored or sent over a network., and automatic documentation generation.

from pydantic import BaseModel

class User(BaseModel):
    name: str
    email: str
    age: int

# Pydantic validates automatically:
user = User(name="Alice", email="alice@example.com", age=30)  # works
user = User(name="Alice", email="alice@example.com", age="not a number")  # raises ValidationError

When you use a Pydantic model as a parameter in a FastAPI endpointWhat is endpoint?A specific URL path on a server that handles a particular type of request, like GET /api/users., the framework automatically parses the request body, validates every field, and returns a detailed error response if validation fails, all without a single line of validation code from you.

03

Automatic APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. documentation

Every FastAPI application gets two interactive documentation interfaces for free.

EndpointInterfaceWhat it does
/docsSwagger UIInteractive, you can send test requests directly from the browser
/redocReDocRead-only, cleaner layout for sharing with consumers

Both are generated from your code's type annotations and Pydantic models. When AI generates a FastAPI app, it includes these endpoints automatically. This means you can spin up the app, visit /docs, and immediately test every endpointWhat is endpoint?A specific URL path on a server that handles a particular type of request, like GET /api/users. without writing a single line of client code or reaching for Postman.

AI pitfall
AI sometimes adds manual OpenAPI schema definitions alongside FastAPI's auto-generated ones, creating duplicates or conflicts. If you see a hand-written openapi_schema dictionary in AI output, it is almost always unnecessary, FastAPI handles this from your type hints.
04

FastAPI vs Flask vs Django RESTWhat is rest?An architectural style for web APIs where URLs represent resources (nouns) and HTTP methods (GET, POST, PUT, DELETE) represent actions on those resources. Framework

Each framework optimizes for a different use case. The right choice depends on what you are building.

Flask

Flask is minimal by design. It gives you a request/response cycle and a routing system. Everything else, validation, serializationWhat is serialization?Converting data from a program's internal format into a string or byte sequence that can be stored or sent over a network., authenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token., database access, you add yourself through extensions. This simplicity makes Flask easy to learn and excellent for small scripts, internal tools, and prototypes.

# Flask - clean and simple, but no built-in validation
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route("/users", methods=["POST"])
def create_user():
    data = request.get_json()
    # Manual validation - you write all of this yourself
    if "name" not in data or "email" not in data:
        return jsonify({"error": "Missing fields"}), 400
    return jsonify({"id": 1, **data}), 201

FastAPI

FastAPI gives you validation, serialization, and documentation out of the box. The same endpointWhat is endpoint?A specific URL path on a server that handles a particular type of request, like GET /api/users. in FastAPI is shorter and safer.

# FastAPI - validation and docs are automatic
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class UserCreate(BaseModel):
    name: str
    email: str

@app.post("/users", status_code=201)
async def create_user(user: UserCreate):
    return {"id": 1, **user.model_dump()}

If the client sends {"name": "Alice"} (missing email), FastAPI automatically returns a 422 Unprocessable Entity with a detailed error message, no manual validation code needed.

Django REST Framework

Django REST Framework (DRF) is the most full-featured option. It provides an ORMWhat is orm?Object-Relational Mapping - a library that lets you interact with a database using your programming language's objects instead of writing raw SQL., admin interface, authentication system, permissions, throttling, paginationWhat is pagination?Splitting a large set of results into smaller pages so the server and client only handle a manageable chunk at a time., and more. It is the right choice for large applications with complex data models and team collaboration needs.

The tradeoff is boilerplateWhat is boilerplate?Repetitive, standardized code that follows a known pattern and appears in nearly every project - like setting up a server or wiring up database connections.. A simple CRUDWhat is crud?Create, Read, Update, Delete - the four basic operations almost every application performs on data. endpoint in DRF requires a serializer class, a viewset or view class, URL configuration, and often model registration. For small APIs or microservicesWhat is microservices?An architecture where an application is split into small, independently deployed services that communicate over the network, each owning its own data., this ceremony slows you down.

05

Decision table

FactorFlaskFastAPIDjango REST Framework
Learning curveLowLow-mediumMedium-high
Built-in validationNoYes (Pydantic)Yes (serializers)
Auto-generated docsNoYesYes (with drf-spectacular)
Async supportLimited (Flask 2.0+)NativeLimited
ORM includedNoNoYes (Django ORM)
Admin panelNoNoYes
Best forPrototypes, small APIs, internal toolsModern APIs, microservices, ML model servingLarge apps, admin-heavy, complex permissions
AI code generation qualityGood, simple enough for AI to get rightExcellent, type hints guide AI outputMixed, lots of boilerplate for AI to hallucinate

When AI suggests a framework for your project, check it against this table. A common AI mistake is recommending Django for a simple three-endpointWhat is endpoint?A specific URL path on a server that handles a particular type of request, like GET /api/users. microservice, or Flask for a project that clearly needs request validation. FastAPI sits in the sweet spot for most modern APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. projects.

AI pitfall
AI sometimes recommends FastAPI for projects that need server-side HTML rendering (traditional web apps with forms and page navigation). FastAPI can serve HTML with Jinja2 templates, but Django or Flask are better choices for template-heavy applications. FastAPI shines when building JSON APIs consumed by frontends or other services.