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.
pip install fastapi[all]conda install -c conda-forge fastapi uvicornFastAPI 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.
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.
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 itemFastAPI uses Pydantic models to validate and parse JSON request bodies.
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.
@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.
# Run your FastAPI app using uvicorn:
# uvicorn main:app --reloadOnce running, visit /docs for Swagger UI or /redoc for ReDoc-generated API docs.
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 commonsAllows reusing common parameters and logic across endpoints.
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.