DEV Community

Suifeng023
Suifeng023

Posted on

How to Build a Production-Ready API in 10 Minutes with FastAPI

How to Build a Production-Ready API in 10 Minutes with FastAPI

I've built APIs with Flask, Django, and Express. Nothing comes close to FastAPI for speed — both in development AND performance.

If you're still building REST APIs with Flask, it's time to stop. FastAPI gives you automatic validation, interactive docs, async support, and type hints — all for free. Here's how to go from zero to a production-ready API in under 10 minutes.


Step 1: Install & Set Up

pip install fastapi uvicorn
Enter fullscreen mode Exit fullscreen mode

That's it. Two packages. No bloat.

Step 2: Write Your First Endpoint

Create main.py:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(title="My API", version="1.0.0")

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True

@app.get("/")
async def root():
    return {"message": "Hello World", "docs": "/docs"}

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    return {"item_id": item_id, "name": f"Item {item_id}"}

@app.post("/items")
async def create_item(item: Item):
    return {"created": item.name, "price": item.price}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run It

uvicorn main:app --reload --host 0.0.0.0 --port 8000
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:8000/docs — you now have interactive Swagger UI for free. No Postman needed.


Why FastAPI Beats Everything Else

1. Auto-Validation with Pydantic

Pass the wrong type? You get a clean 422 error with details:

{
  "detail": [
    {
      "loc": ["body", "price"],
      "msg": "value is not a valid float",
      "type": "type_error.float"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

No need to write if not isinstance(price, float) ever again.

2. Async by Default

import httpx

@app.get("/weather/{city}")
async def get_weather(city: str):
    async with httpx.AsyncClient() as client:
        resp = await client.get(f"https://api.weather.com/{city}")
        return resp.json()
Enter fullscreen mode Exit fullscreen mode

Handle 10x more concurrent requests than synchronous Flask.

3. Automatic OpenAPI Schema

Every endpoint auto-generates:

  • Swagger UI at /docs
  • ReDoc at /redoc
  • OpenAPI JSON at /openapi.json

Your frontend team will love you.

4. Dependency Injection

from fastapi import Depends, HTTPException, Header

async def verify_token(x_token: str = Header(...)):
    if x_token != "my-secret":
        raise HTTPException(status_code=400, detail="Invalid token")
    return x_token

@app.get("/protected")
async def protected(token: str = Depends(verify_token)):
    return {"message": "Access granted"}
Enter fullscreen mode Exit fullscreen mode

Clean, reusable, testable.


Level Up: Database + Auth in 5 More Minutes

Add SQLAlchemy and JWT auth:

pip install sqlalchemy aiomysql python-jose passlib[bcrypt]
Enter fullscreen mode Exit fullscreen mode
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./app.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)
    email = Column(String, unique=True, index=True)

Base.metadata.create_all(bind=engine)
Enter fullscreen mode Exit fullscreen mode

Now you have a full database layer.


Production Deployment Checklist

Before shipping, add these:

  1. CORS Middlewareapp.add_middleware(CORSMiddleware, ...)
  2. Environment Variables — Use pydantic-settings for config
  3. Error Handlers — Custom exception classes
  4. Logging — Structured JSON logs with structlog
  5. Health Check/health endpoint for monitoring
  6. Rate Limiting — Use slowapi middleware
  7. Docker — Multi-stage build for small images
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Enter fullscreen mode Exit fullscreen mode

Performance Numbers

FastAPI isn't just developer-friendly — it's fast:

Framework Requests/sec (JSON) Latency (ms)
FastAPI 27,000+ ~3.5ms
Flask 8,000+ ~12ms
Django 6,500+ ~15ms

(Source: TechEmpower benchmarks)


When to NOT Use FastAPI

  • You need a full admin panel → Use Django
  • You're building a simple microservice with 1 endpoint → Flask is fine
  • Your team has zero Python experience → Consider NestJS or Express

For 90% of API projects, FastAPI is the right choice.


What are you building with FastAPI? Share your projects below! 👇

Top comments (0)