- Published on
Getting Started with FastAPI - The Future of Python APIs
- Authors

- Name
- Sanjeev Sharma
- @webcoderspeed1
Introduction
FastAPI is taking the Python world by storm. It's faster than Flask, easier than Django REST Framework, and comes with automatic interactive documentation out of the box. If you're still building APIs with Flask in 2026, this guide is your sign to switch.
FastAPI is built on top of Starlette (for the web parts) and Pydantic (for the data validation parts). The result? One of the fastest Python web frameworks available — benchmarked close to Node.js and Go.
- Why FastAPI Over Flask or Django?
- Installation
- Your First FastAPI App
- Request Body with Pydantic
- Async Endpoints
- Path Parameters and Query Parameters
- Adding a Database with SQLAlchemy
- Error Handling
- Middleware
- Conclusion
Why FastAPI Over Flask or Django?
Before we dive in, here's a quick comparison of why FastAPI is winning in 2026:
| Feature | Flask | Django REST | FastAPI |
|---|---|---|---|
| Speed | Medium | Medium | Very Fast |
| Auto Docs | ❌ | ❌ | ✅ |
| Type Safety | ❌ | ❌ | ✅ |
| Async Support | Partial | Partial | Full |
| Learning Curve | Low | High | Low |
FastAPI gives you Swagger UI and ReDoc documentation automatically — just by writing your code.
Installation
Start by creating a virtual environment and installing FastAPI:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install fastapi uvicorn
uvicorn is the ASGI server that will run your FastAPI app.
Your First FastAPI App
Create a file called main.py:
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 = None):
return {"item_id": item_id, "q": q}
Run it with:
uvicorn main:app --reload
Now visit http://127.0.0.1:8000/docs and you'll see a beautiful interactive Swagger UI — automatically generated!
Request Body with Pydantic
FastAPI uses Pydantic models for request validation. This is where the magic really happens:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_available: bool = True
@app.post("/items/")
def create_item(item: Item):
return {"item_name": item.name, "price": item.price}
FastAPI will automatically validate the incoming JSON, show errors if the data is wrong, and generate documentation for it. No extra code needed.
Async Endpoints
FastAPI has first-class support for async/await:
import asyncio
from fastapi import FastAPI
app = FastAPI()
@app.get("/async-data")
async def get_async_data():
await asyncio.sleep(1) # Simulating async DB call
return {"data": "This was fetched asynchronously!"}
Using async def allows FastAPI to handle thousands of concurrent requests without blocking — making it ideal for I/O-heavy applications like database queries and external API calls.
Path Parameters and Query Parameters
from fastapi import FastAPI
from enum import Enum
class Category(str, Enum):
tech = "tech"
health = "health"
finance = "finance"
app = FastAPI()
@app.get("/posts/{category}")
def get_posts(category: Category, page: int = 1, limit: int = 10):
return {
"category": category,
"page": page,
"limit": limit
}
FastAPI validates path and query parameters automatically, including Enum types!
Adding a Database with SQLAlchemy
Here's a minimal setup with SQLAlchemy:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session
from database import SessionLocal, User, Base, engine
Base.metadata.create_all(bind=engine)
app = FastAPI()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{user_id}")
def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
return user
Error Handling
FastAPI makes error handling clean and expressive:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
if user_id > 100:
raise HTTPException(status_code=404, detail="User not found")
return {"user_id": user_id}
Middleware
Adding middleware (e.g., CORS) is simple:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
Conclusion
FastAPI is genuinely one of the best things to happen to Python web development. With automatic docs, async support, type safety, and blazing speed, it's the go-to choice for building modern REST APIs in 2026.
Whether you're building a simple CRUD app or a complex microservice, FastAPI has you covered. Give it a try — you won't go back to Flask.