Difficulty: Beginner
FastAPI is a modern, high-performance web framework for building APIs with Python 3.7+ based on standard Python type hints. Created by Sebastian Ramirez and first released in December 2018, FastAPI has rapidly become one of the most popular Python web frameworks alongside Django and Flask. Its key selling points are speed, developer experience, and automatic documentation generation.
FastAPI is built on top of two foundational Python libraries: Starlette for the web framework internals (routing, middleware, WebSocket support) and Pydantic for data validation and serialization. Starlette provides the ASGI (Asynchronous Server Gateway Interface) foundation, which means FastAPI can handle asynchronous requests natively using Python's async/await syntax. Pydantic leverages Python type annotations to validate incoming data, serialize outgoing data, and generate JSON Schema definitions automatically.
One of FastAPI's most celebrated features is its automatic interactive API documentation. When you create an API with FastAPI, it automatically generates two documentation interfaces: Swagger UI (available at /docs) and ReDoc (available at /redoc). These are not static pages - they are fully interactive, allowing developers to test API endpoints directly from the browser. This documentation is generated from your Python type hints and Pydantic models, so it is always in sync with your actual code.
Performance is another major differentiator. FastAPI is one of the fastest Python web frameworks available, with performance comparable to Node.js and Go frameworks. This speed comes from Starlette's ASGI implementation and the use of Uvicorn as the ASGI server (which is built on uvloop and httptools). In benchmarks, FastAPI consistently outperforms Flask and Django REST Framework by significant margins.
FastAPI embraces Python's type hint system extensively. Every parameter, request body, and response is annotated with types. This serves multiple purposes: the framework uses types for automatic request validation and parsing, the documentation generator uses them to describe the API, and your IDE can provide autocomplete and type checking. This means you write the type once and get validation, documentation, and editor support for free.
Compared to Flask, FastAPI offers built-in data validation (Flask requires extensions like Marshmallow or WTForms), async support (Flask is synchronous by default), and automatic docs (Flask needs Flask-RESTX or similar). Compared to Django REST Framework, FastAPI is lighter weight, faster, and more focused on API development specifically. However, Django offers a full-featured ORM, admin panel, authentication system, and template engine out of the box, making it better suited for full-stack web applications.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
This is the simplest possible FastAPI application. We import FastAPI, create an instance, and define a single route using the @app.get decorator. The function returns a dictionary which FastAPI automatically serializes to JSON.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "query": q}
# GET /items/42?q=search
# Response: {"item_id": 42, "query": "search"}
# GET /items/abc
# Response: 422 Validation Error (item_id must be int)
Type hints serve double duty: item_id: int tells FastAPI to parse the path parameter as an integer and return a 422 error if it cannot. The optional query parameter q uses str | None = None to indicate it is not required.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI(
title="My API",
description="A sample API with automatic docs",
version="1.0.0",
)
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
# Visit http://localhost:8000/docs for Swagger UI
# Visit http://localhost:8000/redoc for ReDoc
FastAPI reads the Pydantic model and function signatures to generate OpenAPI schema automatically. The /docs endpoint provides Swagger UI where you can try out endpoints interactively. The /redoc endpoint provides an alternative documentation layout.
# Flask approach (requires extra libraries for validation)
from flask import Flask, request, jsonify
flask_app = Flask(__name__)
@flask_app.route("/items", methods=["POST"])
def create_item_flask():
data = request.get_json()
# Manual validation needed
if "name" not in data or "price" not in data:
return jsonify({"error": "Missing fields"}), 400
return jsonify({"item_name": data["name"]})
# -------------------------------------------
# FastAPI approach (validation is built-in)
from fastapi import FastAPI
from pydantic import BaseModel
fastapi_app = FastAPI()
class Item(BaseModel):
name: str
price: float
@fastapi_app.post("/items")
def create_item_fastapi(item: Item):
# Validation happens automatically
return {"item_name": item.name}
In Flask you must manually parse JSON, validate fields, and handle errors. FastAPI handles all of this automatically through Pydantic models. Invalid requests receive detailed 422 error responses without any manual validation code.
FastAPI, Python, Web Framework, Type Hints, Automatic Docs