Kritim Yantra
Apr 14, 2025
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python. It's designed to be easy to use, intuitive, and highly efficient. If you're familiar with Python and want to build APIs quickly, FastAPI is an excellent choice.
In this guide, we'll cover:
FastAPI is a Python framework for building web APIs. It is built on top of Starlette (for web server functionality) and Pydantic (for data validation). Some key features include:
Here’s why developers love FastAPI:
✅ Blazing fast performance (thanks to Starlette and Pydantic)
✅ Automatic API documentation (Swagger & ReDoc)
✅ Data validation using Pydantic models
✅ Easy to learn (similar to Flask but more powerful)
✅ Asynchronous support (works well with async/await)
✅ Production-ready (used by companies like Uber, Netflix, and Microsoft)
First, install FastAPI and an ASGI server (like Uvicorn or Hypercorn):
pip install fastapi uvicorn
Create a file main.py
:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, FastAPI!"}
uvicorn main:app --reload
--reload
enables auto-reload during development.http://127.0.0.1:8000
to see your API response.http://127.0.0.1:8000/docs
http://127.0.0.1:8000/redoc
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
item_id
is automatically converted to an integer.@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
http://127.0.0.1:8000/items/?skip=5&limit=20
FastAPI uses Pydantic models to define request bodies.
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items/")
def create_item(item: Item):
return {"item": item}
curl
:curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name":"Laptop","price":999.99}'
FastAPI automatically validates data using Pydantic.
from pydantic import BaseModel, Field
class User(BaseModel):
username: str = Field(min_length=3, max_length=20)
age: int = Field(gt=0, lt=120)
You can define what data your API returns:
@app.post("/users/", response_model=User)
def create_user(user: User):
return user
User
are returned.FastAPI provides HTTPException
for custom errors:
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
Install SQLAlchemy:
pip install sqlalchemy
Example with SQLite:
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_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)
email = Column(String, unique=True)
Base.metadata.create_all(bind=engine)
Install Motor (async MongoDB driver):
pip install motor
Example:
from motor.motor_asyncio import AsyncIOMotorClient
client = AsyncIOMotorClient("mongodb://localhost:27017")
db = client.test_db
collection = db.users
FastAPI supports OAuth2, JWT, and API keys.
Install python-jose
and passlib
:
pip install python-jose[cryptography] passlib[bcrypt]
Example:
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
def read_current_user(token: str = Depends(oauth2_scheme)):
return {"token": token}
FastAPI can be deployed using:
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
Run:
docker build -t fastapi-app .
docker run -d -p 80:80 fastapi-app
✔ Use Pydantic models for data validation
✔ Enable CORS if your API is used by frontend apps
✔ Use environment variables for configurations
✔ Implement rate limiting to prevent abuse
✔ Write unit tests (using pytest
)
✔ Use async/await for I/O-bound operations
FastAPI is a powerful, easy-to-use framework for building APIs in Python. It combines speed, simplicity, and modern features like automatic docs, data validation, and async support. Whether you're building a small API or a large-scale application, FastAPI is a great choice.
Happy coding! 🚀
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google