FastAPI

Language: Python

Web

FastAPI was created by Sebastián Ramírez in 2018. Its goal was to provide a framework that is fast (high-performance), easy to use, and fully compatible with modern Python features like type hints and async programming. It automatically generates OpenAPI and Swagger documentation for your APIs, making it a popular choice for building RESTful services and microservices.

FastAPI is a modern, high-performance Python web framework for building APIs with automatic interactive documentation, leveraging Python type hints for data validation and serialization.

Installation

pip: pip install fastapi[all]
conda: conda install -c conda-forge fastapi uvicorn

Usage

FastAPI allows you to define API endpoints using Python function definitions with type annotations. It supports async operations, request validation, automatic docs generation, dependency injection, security, and more.

Simple GET endpoint

from fastapi import FastAPI
app = FastAPI()

@app.get('/items/{id}')
async def read_item(id: int):
    return {'id': id}

Defines a GET endpoint at /items/{id}. The 'id' parameter is type-checked as an integer automatically.

POST endpoint with JSON body

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.post('/items/')
async def create_item(item: Item):
    return item

FastAPI uses Pydantic models to validate and parse JSON request bodies.

Query parameters with validation

from fastapi import FastAPI, Query
app = FastAPI()

@app.get('/search')
async def search(q: str = Query(..., min_length=3, max_length=50)):
    return {'query': q}

Defines a query parameter 'q' with minimum and maximum length validation.

Path parameters with type enforcement

@app.get('/users/{user_id}')
async def get_user(user_id: int):
    return {'user_id': user_id}

Ensures the user_id path parameter is an integer.

Automatic interactive API docs

# Run your FastAPI app using uvicorn:
# uvicorn main:app --reload

Once running, visit /docs for Swagger UI or /redoc for ReDoc-generated API docs.

Dependency injection

from fastapi import Depends

async def common_parameters(q: str = None, limit: int = 10):
    return {'q': q, 'limit': limit}

@app.get('/items/')
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

Allows reusing common parameters and logic across endpoints.

Error Handling

422 Unprocessable Entity: Occurs when request body validation fails. Ensure JSON fields match Pydantic model types.
404 Not Found: Use proper path parameters and raise HTTPException with status_code=404 when resources are missing.

Best Practices

Use Pydantic models for request validation and response models.

Leverage async endpoints for IO-bound operations.

Use dependency injection for reusable logic like authentication or DB connections.

Keep path and query parameters explicit for clarity.

Include meaningful tags and summaries for better auto-generated documentation.