What is FastAPI and what are its key features?
FastAPI is a modern, high-performance Python web framework for building APIs. It was created by Sebastian Ramirez and first released in 2018.
Key features:
- Fast: Built on Starlette and Uvicorn (ASGI), performance comparable to Node.js and Go
- Type hints: Leverages Python type annotations for automatic validation, serialization, and documentation
- Automatic docs: Generates interactive Swagger UI and ReDoc documentation from your code
- Data validation: Uses Pydantic for request/response validation with detailed error messages
- Async support: Native
async/awaitsupport for high-concurrency workloads - Dependency injection: Built-in DI system for clean, testable code
- Standards-based: Fully compliant with OpenAPI 3.1 and JSON Schema
- Editor support: Excellent autocomplete and type checking due to type hints
Why it is popular:
FastAPI combines the ease of use of Flask with the performance of async frameworks and the automatic validation of type-safe languages. It reduces bugs by catching type errors at request time rather than deep in business logic.
# FastAPI at a glance
import FastAPI
app = create FastAPI application
@app.GET("/items/{id}")
function get_item(id: integer, query: string = default):
# id is auto-validated as integer
# query is auto-validated as string with default
return {"id": id, "query": query}
# Auto-generated docs at /docs (Swagger) and /redoc (ReDoc)
# Auto request validation, serialization, error responses
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = "default"):
"""item_id is validated as int, q is an optional query param."""
return {"item_id": item_id, "q": q}
# Run with: uvicorn main:app --reload
# Visit http://127.0.0.1:8000/docs for Swagger UI
# Visit http://127.0.0.1:8000/redoc for ReDoc
# Quick verification with TestClient
from fastapi.testclient import TestClient
client = TestClient(app)
response = client.get("/items/42?q=search")
print(response.json())
print(response.status_code)
- •FastAPI is built on Starlette (web) and Pydantic (data validation)
- •Type hints drive validation, serialization, and auto-generated docs
- •Native async/await support with ASGI for high concurrency
- •Automatic interactive API docs at /docs and /redoc
- •FastAPI requires Python 3.8+ (3.10+ recommended for modern type syntax)
- •You need an ASGI server like Uvicorn to run FastAPI -- it cannot run standalone like Flask's development server
- •FastAPI is the framework, Uvicorn is the server -- they are separate packages