Skip to main content

Overview

FastAPI is a modern, high-performance web framework for building APIs with Python 3.10+ based on standard Python type hints. It is designed to be easy to use, fast to code, and ready for production.

The Problem: API Boilerplate​

Building a robust API typically requires writing significant amounts of code for:

  • Data Validation: Ensuring incoming request data matches expected types and constraints.
  • Serialization: Converting Python objects to JSON for responses.
  • Documentation: Keeping API specifications (like OpenAPI) in sync with the actual implementation.
  • Dependency Management: Handling shared logic like database connections or authentication.

FastAPI solves these by leveraging Python's type system to automate these tasks, allowing you to focus on your business logic.

Core Concepts​

FastAPI is built on two main pillars: Starlette for the web parts and Pydantic for the data parts.

  • Path Operations: Functions decorated with methods like @app.get("/") or @app.post("/items") that handle specific HTTP requests.
  • Type Hints as Validation: By declaring types for function parameters (e.g., item_id: int), FastAPI automatically validates the request and returns clear error messages if the data is invalid.
  • Pydantic Models: Classes that define the structure of request bodies and response data. They provide deep validation and automatic JSON conversion.
  • Dependency Injection: A system using Depends() to share reusable logic across multiple routes, such as database sessions, security checks, or configuration.
  • Automatic Docs: FastAPI generates interactive API documentation (Swagger UI and ReDoc) automatically from your code and type hints.

How It Works​

FastAPI acts as a high-level orchestrator that maps incoming HTTP requests to your Python functions.

  1. Request Arrival: An ASGI server (like Uvicorn) receives a request and passes it to the FastAPI app.
  2. Parameter Extraction: FastAPI extracts data from the URL path, query parameters, headers, cookies, or the request body.
  3. Validation: Data is validated against your type hints and Pydantic models.
  4. Dependency Resolution: Any declared dependencies are executed and their results are passed to your function.
  5. Function Execution: Your path operation function runs.
  6. Response Serialization: The return value is validated against your response model and converted to JSON.

Use Cases​

1. Simple GET Endpoint​

Define a route that takes a path parameter and a query parameter.

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, "q": q}

2. POST with Pydantic Model​

Validate and process a JSON request body.

from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None

app = FastAPI()

@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}

3. Dependency Injection​

Share logic like authentication or database access.

from typing import Annotated
from fastapi import Depends, FastAPI

app = FastAPI()

async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}

@app.get("/users/")
async def read_users(commons: Annotated[dict, Depends(common_parameters)]):
return commons

When to Use FastAPI​

  • High Performance: When you need the speed of Node.js or Go in Python.
  • Developer Productivity: When you want to build APIs quickly with minimal boilerplate and excellent editor support (autocompletion everywhere).
  • Modern Python: When you are using Python 3.10+ and want to leverage modern features like async/await and type hints.
  • Automatic Documentation: When you want your API to be self-documenting for frontend teams or external users.

When Not to Use FastAPI​

  • Full-Stack Monoliths: If you need a "batteries-included" framework with a built-in ORM, admin interface, and template engine (consider Django).
  • Legacy Systems: If you are restricted to older Python versions (< 3.10).
  • Simple Scripts: For very simple one-off scripts where a web server is overkill.

Integration & Stack Compatibility​

FastAPI is highly compatible with the modern Python ecosystem:

  • Servers: Runs on any ASGI server like uvicorn or hypercorn.
  • Databases: Works with any ORM or database driver (SQLAlchemy, Tortoise ORM, Motor, etc.).
  • Data Validation: Deeply integrated with pydantic.
  • Standards: Fully compliant with OpenAPI (formerly Swagger) and JSON Schema.

Getting Started Pointers​

  • Install with pip install "fastapi[standard]" to get the CLI and server.
  • Run your app using the CLI: fastapi dev main.py.
  • Visit http://127.0.0.1:8000/docs to see your automatic interactive documentation.

FAQ​

Is FastAPI faster than Flask? Yes, FastAPI is significantly faster because it is built on Starlette and supports asynchronous programming (async/await) natively.

Do I have to use async def? No. You can use regular def for synchronous code. FastAPI will run them in a separate thread pool to avoid blocking the event loop.

How do I handle database connections? FastAPI doesn't force a specific database library. You typically use the Dependency Injection system to create and close database sessions for each request.

Does it support WebSockets? Yes, FastAPI has first-class support for WebSockets, inherited from Starlette.