FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to be easy to use, highly performant, and reduce development time.
Key Features and Concepts:
1. High Performance: FastAPI is one of the fastest Python frameworks available, comparable to Node.js and Go. This is achieved by leveraging Starlette for the web parts and Pydantic for data validation and serialization.
2. Type Hinting: It fully utilizes standard Python type hints (from `typing`) for declaring request parameters, body, and return types. This allows for excellent editor support (autocompletion, type checking) and ensures data validation.
3. Automatic API Documentation: FastAPI automatically generates interactive API documentation based on the OpenAPI (formerly Swagger) standard. This includes Swagger UI and ReDoc, accessible directly from your running API, making it easy to test and understand your endpoints.
4. Data Validation and Serialization: It uses Pydantic to handle data validation, serialization, and deserialization. You define data schemas using Pydantic models, and FastAPI ensures that incoming requests conform to these schemas, providing clear error messages if not.
5. Asynchronous Support (`async`/`await`): Built on ASGI (Asynchronous Server Gateway Interface), FastAPI fully supports asynchronous operations, allowing you to write highly concurrent code for I/O-bound tasks (e.g., database queries, external API calls).
6. Dependency Injection System: It has a powerful and easy-to-use dependency injection system that allows you to manage database connections, authentication, and other common components efficiently.
7. Security: Provides tools for easy integration of security features like OAuth2 with JWT tokens, API keys, and HTTP Basic authentication.
8. Developer Experience: The framework's design leads to fewer bugs, better code quality, and significantly reduced development time due to its strong typing and automatic features.
How it Works:
FastAPI integrates several powerful libraries:
- Starlette: Handles the core web parts (routing, middleware, HTTP requests, WebSockets, etc.).
- Pydantic: Provides data validation, serialization, and settings management.
- Uvicorn: An ASGI server that runs your FastAPI application.
When you define an endpoint (a 'path operation') using decorators like `@app.get()`, `@app.post()`, etc., FastAPI inspects your function's type hints. It then uses Pydantic to validate incoming data against those hints, serializes responses, and generates the OpenAPI documentation automatically.
Example Code
First, install FastAPI and an ASGI server like Uvicorn:
pip install fastapi uvicorn pydantic
from typing import Optional
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel
Initialize the FastAPI app
app = FastAPI(
title="My Awesome FastAPI App",
description="A simple example to demonstrate FastAPI's capabilities."
)
Define a Pydantic model for request body validation
class Item(BaseModel):
name: str
price: float
description: Optional[str] = None
tax: Optional[float] = None
Define a root path operation
@app.get("/", summary="Root endpoint")
async def read_root():
return {"message": "Welcome to FastAPI! Visit /docs for API documentation."}
Define a path operation with a path parameter and query parameter
@app.get("/items/{item_id}", response_model=Item, summary="Get a single item by ID")
async def read_item(item_id: int, q: Optional[str] = None):
Simulate a database lookup
fake_items_db = {"foo": {"name": "Foo", "price": 50.2, "description": "A tasty foo"}}
if str(item_id) not in fake_items_db:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Item with ID {item_id} not found"
)
item = fake_items_db[str(item_id)]
if q:
item["description"] += f" - Query: {q}"
return item
Define a path operation that accepts a request body using the Pydantic model
@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED, summary="Create a new item")
async def create_item(item: Item):
item is automatically validated against the Item Pydantic model
item_dict = item.dict()
if item.price > 100:
item_dict.update({"tax": item.price - 0.1})
print(f"Creating item: {item_dict}") For demonstration
return item_dict Return the validated and possibly modified item
To run this application:
1. Save the code above as `main.py`.
2. Open your terminal or command prompt in the same directory.
3. Run the Uvicorn server: `uvicorn main:app --reload`
`--reload` makes the server restart automatically on code changes.
4. Access your API:
- Open your browser to `http://127.0.0.1:8000`
- Check the interactive API docs at `http://127.0.0.1:8000/docs` (Swagger UI)
- Or `http://127.0.0.1:8000/redoc` (ReDoc)








FastAPI