http://127.0.0.1:8000/redoc → Alternative documentation view
FastAPI auto-generates documentation using OpenAPI — no extra code needed.
Adding CORS (optional — for frontend apps)
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # list specific domains in production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
With Database Example (SQLAlchemy)
Install DB dependencies first:
pip install sqlalchemy
Sample setup:
from fastapi import FastAPI, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
This allows injecting DB sessions into your routes.
Why FastAPI?
Feature
Benefit
Very Fast
Built on ASGI + Starlette
Auto Docs
Swagger & ReDoc
Pydantic Models
Validation + Serialization
Async Ready
Supports async/await
Production Friendly
Works well with Docker, Gunicorn, Kubernetes
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Step 1 — Install FastAPI & Uvicorn
Step 2 — Create an API file
Create a file named
main.py:Step 3 — Run the API server
main→ filename (main.py)app→ FastAPI instance--reload→ auto-reload on code changes (useful during development)Example CRUD REST API
Below is a complete example for managing items in memory.
Test the API
After running
uvicorn, open your browser:http://127.0.0.1:8000/docs→ FastAPI’s Swagger UIhttp://127.0.0.1:8000/redoc→ Alternative documentation viewFastAPI auto-generates documentation using OpenAPI — no extra code needed.
Adding CORS (optional — for frontend apps)
With Database Example (SQLAlchemy)
Install DB dependencies first:
Sample setup:
This allows injecting DB sessions into your routes.
Why FastAPI?
async/await