FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It's built on top of Starlette for the web parts and Pydantic for the data parts. FastAPI is designed to create RESTful APIs quickly and efficiently, and it comes with built-in support for data validation, authentication, and interactive API documentation.
Key Features of FastAPI
- Type Checking: Uses Python type hints in conjunction with Pydantic models to provide strong type checking.
- Automatic Documentation: Comes with automatic interactive API docs (Swagger UI) and another ReDoc.
- Authentication: Easy integration with OAuth2 and JWT for secure authentication.
- High Performance: One of the fastest frameworks available, on par with NodeJS and Go.
- Asynchronous Support: Native support for asynchronous request handling.
- Dependency Injection: Built-in support for reusable dependencies.
API Documentation
API documentation is crucial when building APIs. It serves as a contract that describes how the API functions and how it should be used. FastAPI provides two types of auto-generated documentation:
- Swagger UI: Accessible by default at
/docs
. It provides an interactive interface for testing the API endpoints. - ReDoc: Accessible at
/redoc
, it provides a more aesthetic view but is non-interactive.
Example Code
Here's a simple FastAPI application with an API endpoint and its documentation:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str
@app.post("/items/")
async def create_item(item: Item):
return {"name": item.name, "description": item.description}
When you run this application, you can visit http://127.0.0.1:8000/docs
to see the automatically generated documentation.
Further Exploration
- FastAPI Advanced Features
- API Documentation Best Practices
- OAuth2 with FastAPI
- Asynchronous Programming