DEV Community

Joey Umanito
Joey Umanito

Posted on

Build a Production REST API with Python FastAPI in 10 Minutes

Building REST APIs is one of the most in-demand skills in web development. In this guide, I'll show you how to build a production-ready REST API with Python and FastAPI in under 10 minutes.

Why FastAPI?

FastAPI is the fastest-growing Python web framework because it's:

  • Fast: One of the fastest Python frameworks available
  • Easy: Automatic API documentation with Swagger UI
  • Modern: Built with Python type hints for better code quality
  • Production-ready: Used by major companies like Netflix, Uber, and Microsoft

Step 1: Install FastAPI

pip install fastapi uvicorn python-multipart
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Your First API

Create a file called main.py:

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional

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

# Data model
class Item(BaseModel):
    name: str
    price: float
    description: Optional[str] = None

# In-memory storage (use a database in production)
items = {}

@app.get("/")
def root():
    return {"message": "Welcome to My REST API"}

@app.get("/items")
def get_items():
    return {"items": list(items.values())}

@app.get("/items/{item_id}")
def get_item(item_id: int):
    if item_id not in items:
        return {"error": "Item not found"}, 404
    return items[item_id]

@app.post("/items/{item_id}")
def create_item(item_id: int, item: Item):
    items[item_id] = item.dict()
    return {"message": "Item created", "item": item}

@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    if item_id not in items:
        return {"error": "Item not found"}, 404
    items[item_id] = item.dict()
    return {"message": "Item updated", "item": item}

@app.delete("/items/{item_id}")
def delete_item(item_id: int):
    if item_id not in items:
        return {"error": "Item not found"}, 404
    del items[item_id]
    return {"message": "Item deleted"}
Enter fullscreen mode Exit fullscreen mode

Step 3: Run Your API

uvicorn main:app --reload
Enter fullscreen mode Exit fullscreen mode

Your API is now running at http://localhost:8000!

Visit http://localhost:8000/docs for the automatic Swagger UI documentation.

Step 4: Add Authentication

For production APIs, always add authentication:

from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

security = HTTPBearer()

def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
    token = credentials.credentials
    if token != "your-secret-token":
        raise HTTPException(status_code=401, detail="Invalid token")
    return token

@app.get("/protected")
def protected_route(token: str = Depends(verify_token)):
    return {"message": "You have access!", "token": token}
Enter fullscreen mode Exit fullscreen mode

Step 5: Deploy to Production

The easiest way to deploy FastAPI is with Docker:

FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
Enter fullscreen mode Exit fullscreen mode

Best Practices for REST APIs

  1. Use proper HTTP status codes (200, 201, 400, 401, 404, 500)
  2. Version your API (/api/v1/items)
  3. Validate all inputs with Pydantic models
  4. Add rate limiting to prevent abuse
  5. Document with OpenAPI (FastAPI does this automatically!)
  6. Use environment variables for secrets and configuration

Need a Custom REST API Built for You?

If you need a professional REST API built for your project — whether it's a mobile app backend, data processing pipeline, or third-party integration — I can help!

Check out my Fiverr gig:

I build clean, documented, production-ready APIs with full testing and deployment support!


Questions about building REST APIs? Drop a comment below!

Top comments (0)