Tutorials Python Python Project — REST API
Ch 56 / 58
Python Project 30 min build Chapter 56 of 58

Python Project: Build a REST API

Build a production-ready REST API from scratch using Python and FastAPI — the modern, high-performance framework used by Netflix, Uber, and Microsoft. This project covers creating RESTful endpoints, Pydantic data validation, automatic documentation, CRUD operations with an in-memory store, error handling, JWT authentication, and deployment. By the end you'll have a fully functional API that can be consumed by any frontend, mobile app, or another service.

What you'll build in this chapter
v1 — FastAPI setup & first GET endpoint
v2 — Pydantic models & request validation
v3 — Full CRUD — GET, POST, PUT, PATCH, DELETE
v4 — HTTP error handling & custom responses
v5 — JWT authentication & protected routes
Bonus — Flask alternative & deployment tips
Advertisement

REST API Overview — Architecture & HTTP Methods

A REST API (Representational State Transfer Application Programming Interface) is a standardised way for applications to communicate over HTTP. Understanding the request lifecycle and CRUD-to-HTTP mapping is foundational:

FastAPI request lifecycle — from client to response
1. Client — sends HTTP request (browser, mobile app, curl, requests)
▼
HTTP over TCP/IP
2. FastAPI Router — matches URL pattern to handler function
▼
dependency injection
3. Pydantic — validates request body, path & query params, raises 422 on error
▼
typed Python data
4. Route Handler — business logic, DB queries, transforms data
▼
JSON serialisation
5. JSON Response — status code + JSON body sent back to client
CRUD operations → HTTP methods → endpoints
GET
/items
Read — list all items
GET
/items/{id}
Read — get one item by ID
POST
/items
Create — add new item
PUT
/items/{id}
Update — replace entire item
PATCH
/items/{id}
Update — partial field update
DELETE
/items/{id}
Delete — remove item
REST API build roadmap — 5 progressive versions
1
v1 — FastAPI Setup & First Endpoints
pip install, uvicorn server, GET endpoint, path parameters, query params, auto docs at /docs.
~30 lines
2
v2 — Pydantic Models & POST
BaseModel, Field validation, Optional fields, response_model, in-memory dict store.
~55 lines
3
v3 — Full CRUD Operations
All 5 HTTP methods, PUT/PATCH update logic, DELETE, pagination with limit/offset.
~90 lines
4
v4 — Error Handling & Middleware
HTTPException, custom exception handlers, CORS middleware, request logging, validation errors.
~120 lines
5
v5 — JWT Authentication
OAuth2PasswordBearer, JWT tokens (python-jose), password hashing (passlib), protected routes.
~160 lines
FastAPI
Modern async API framework
Uvicorn
ASGI server for FastAPI
Pydantic
Data validation & schemas
python-jose
JWT token creation/verify
passlib
Password hashing (bcrypt)
Swagger UI
Auto docs at /docs

Version 1 — FastAPI Setup & First Endpoints

Install: pip install fastapi uvicorn. Run with: uvicorn main:app --reload. FastAPI auto-generates interactive docs at http://localhost:8000/docs.

Python — main_v1.py
from fastapi import FastAPI, Query, Path
from typing import Optional

app = FastAPI(
    title="K2infocom API",
    description="A sample REST API built with FastAPI",
    version="1.0.0",
)

# ── Basic GET endpoint ───────────────────────────────
@app.get("/")
def root():
    return {"message": "Welcome to K2infocom API!", "version": "1.0"}

# ── Path parameter ───────────────────────────────────
@app.get("/items/{item_id}")
def get_item(
    item_id: int = Path(..., ge=1, description="Item ID (must be ≥ 1)")
):
    return {"item_id": item_id, "name": f"Item {item_id}"}

# ── Query parameters ─────────────────────────────────
@app.get("/items/")
def list_items(
    skip:  int = Query(0,   ge=0,  description="Skip N items"),
    limit: int = Query(10,  ge=1, le=100, description="Max items to return"),
    search: Optional[str] = Query(None, description="Search term"),
):
    # GET /items/?skip=0&limit=5&search=python
    return {"skip": skip, "limit": limit, "search": search}

# ── Health check ─────────────────────────────────────
@app.get("/health")
def health_check():
    from datetime import datetime
    return {"status": "ok", "timestamp": datetime.utcnow().isoformat()}

# ── Run with: uvicorn main_v1:app --reload ───────────
# Visit: http://localhost:8000/docs  → Swagger UI
#        http://localhost:8000/redoc → ReDoc

Version 2 — Pydantic Models & POST Endpoint

Pydantic BaseModel defines the shape of request and response data. FastAPI uses it for automatic validation, serialisation, and documentation generation.

Python — main_v2.py
from fastapi import FastAPI
from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime
import uuid

app = FastAPI(title="Products API")

# ── Pydantic models ───────────────────────────────────
class ProductCreate(BaseModel):
    """Data required to CREATE a product."""
    name:        str   = Field(..., min_length=2, max_length=100,
                                  examples=["Python Handbook"])
    description: str   = Field("", max_length=500)
    price:       float = Field(..., gt=0, description="Price must be > 0")
    category:    str   = Field("general")
    in_stock:    bool  = True

    @field_validator("name")
    @classmethod
    def name_must_not_be_empty(cls, v: str) -> str:
        if v.strip() == "":
            raise ValueError("Name cannot be whitespace-only")
        return v.strip()

class Product(ProductCreate):
    """Full product including server-generated fields."""
    id:         str      = Field(default_factory=lambda: str(uuid.uuid4())[:8])
    created_at: datetime = Field(default_factory=datetime.utcnow)

# ── In-memory store ───────────────────────────────────
products_db: dict[str, Product] = {}

# ── POST — create ─────────────────────────────────────
@app.post("/products",
          response_model=Product,
          status_code=201,
          summary="Create a new product")
def create_product(product_data: ProductCreate) -> Product:
    product = Product(**product_data.model_dump())
    products_db[product.id] = product
    return product

# ── GET all ───────────────────────────────────────────
@app.get("/products", response_model=list[Product])
def get_products() -> list[Product]:
    return list(products_db.values())

# ── GET one ───────────────────────────────────────────
@app.get("/products/{product_id}", response_model=Product)
def get_product(product_id: str) -> Product:
    if product_id not in products_db:
        from fastapi import HTTPException
        raise HTTPException(status_code=404,
                             detail=f"Product '{product_id}' not found")
    return products_db[product_id]
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 FastAPI Django & DRF REST APIs JWT Auth PostgreSQL Docker & AWS Real Projects

Version 3 — Full CRUD Operations

Complete all five HTTP methods — GET (list & single), POST (create), PUT (replace), PATCH (partial update), and DELETE. Add pagination with skip and limit query parameters.

Python — main_v3_crud.py
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, Field
from typing import Optional
import uuid

app = FastAPI()

class ProductCreate(BaseModel):
    name:     str   = Field(..., min_length=2)
    price:    float = Field(..., gt=0)
    category: str   = "general"
    in_stock: bool  = True

class ProductUpdate(BaseModel):         # PATCH — all fields optional
    name:     Optional[str]   = None
    price:    Optional[float] = None
    category: Optional[str]   = None
    in_stock: Optional[bool]  = None

class Product(ProductCreate):
    id: str = Field(default_factory=lambda: str(uuid.uuid4())[:8])

db: dict[str, Product] = {}    # in-memory store

def get_or_404(product_id: str) -> Product:
    if product_id not in db:
        raise HTTPException(404, f"Product {product_id} not found")
    return db[product_id]

# ── GET all — with pagination ─────────────────────────
@app.get("/products", response_model=list[Product])
def list_products(skip: int = Query(0, ge=0),
                    limit: int = Query(10, ge=1, le=100)):
    items = list(db.values())
    return items[skip : skip + limit]

# ── GET one ───────────────────────────────────────────
@app.get("/products/{product_id}", response_model=Product)
def get_product(product_id: str): return get_or_404(product_id)

# ── POST — create ─────────────────────────────────────
@app.post("/products", response_model=Product, status_code=201)
def create_product(data: ProductCreate) -> Product:
    p = Product(**data.model_dump())
    db[p.id] = p; return p

# ── PUT — full replace ────────────────────────────────
@app.put("/products/{product_id}", response_model=Product)
def update_product(product_id: str, data: ProductCreate) -> Product:
    get_or_404(product_id)
    updated = Product(id=product_id, **data.model_dump())
    db[product_id] = updated; return updated

# ── PATCH — partial update ────────────────────────────
@app.patch("/products/{product_id}", response_model=Product)
def patch_product(product_id: str, data: ProductUpdate) -> Product:
    existing = get_or_404(product_id)
    update_data = data.model_dump(exclude_unset=True)   # only set fields
    updated = existing.model_copy(update=update_data)
    db[product_id] = updated; return updated

# ── DELETE ────────────────────────────────────────────
@app.delete("/products/{product_id}", status_code=204)
def delete_product(product_id: str):
    get_or_404(product_id)
    del db[product_id]    # 204 No Content — no return value

Version 4 — Error Handling & CORS Middleware

Production APIs need consistent error responses, CORS headers for frontend access, and request logging. FastAPI's middleware system makes this clean and composable.

Python — main_v4_errors.py
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
import time, logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("api")

app = FastAPI()

# ── CORS — allow any React/Vue/mobile frontend ────────
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],            # production: specific domains
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# ── Request timing middleware ─────────────────────────
@app.middleware("http")
async def log_requests(request: Request, call_next):
    t0 = time.time()
    response = await call_next(request)
    ms = (time.time() - t0) * 1000
    logger.info(f"{request.method} {request.url.path} → {response.status_code} ({ms:.1f}ms)")
    response.headers["X-Response-Time"] = f"{ms:.1f}ms"
    return response

# ── Standard error response shape ────────────────────
def error_response(status: int, message: str, detail=None) -> dict:
    return {"success": False, "status": status,
             "message": message, "detail": detail}

# ── Custom 404 handler ───────────────────────────────
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc: HTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content=error_response(exc.status_code, exc.detail),
    )

# ── Custom 422 validation error handler ──────────────
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request, exc: RequestValidationError):
    errors = [{"field": e["loc"][-1], "msg": e["msg"]}
              for e in exc.errors()]
    return JSONResponse(
        status_code=422,
        content=error_response(422, "Validation failed", errors),
    )

# Example error-safe endpoint
@app.get("/items/{item_id}")
def get_item(item_id: str):
    if item_id not in db:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"success": True, "data": db[item_id]}

Version 5 — JWT Authentication & Protected Routes

Install: pip install python-jose[cryptography] passlib[bcrypt]. Implement a login endpoint that returns a JWT token, then protect specific routes with Depends(get_current_user).

Python — auth_v5.py
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from datetime import datetime, timedelta, timezone

# ── Config ────────────────────────────────────────────
SECRET_KEY   = "your-secret-key-keep-it-safe-in-env-vars"
ALGORITHM    = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

app = FastAPI()

# ── Fake user database ────────────────────────────────
fake_users = {
    "alice": {"username": "alice", "role": "admin",
               "hashed_password": pwd_context.hash("secret123")},
    "bob":   {"username": "bob",   "role": "user",
               "hashed_password": pwd_context.hash("password")},
}

# ── Helpers ───────────────────────────────────────────
def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)

def create_access_token(data: dict) -> str:
    payload = data.copy()
    payload["exp"] = (datetime.now(timezone.utc)
                       + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
    creds_error = HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or expired token",
        headers={"WWW-Authenticate": "Bearer"},
    )
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username: raise creds_error
    except JWTError: raise creds_error
    user = fake_users.get(username)
    if not user: raise creds_error
    return user

# ── POST /token — login ───────────────────────────────
@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
    user = fake_users.get(form.username)
    if not user or not verify_password(form.password, user["hashed_password"]):
        raise HTTPException(401, "Incorrect username or password")
    token = create_access_token({"sub": user["username"],
                                   "role": user["role"]})
    return {"access_token": token, "token_type": "bearer"}

# ── Protected route ───────────────────────────────────
@app.get("/me")
def get_me(current_user: dict = Depends(get_current_user)):
    return {"username": current_user["username"],
             "role": current_user["role"]}

# Admin-only route with role check
@app.delete("/admin/reset")
def admin_reset(current_user: dict = Depends(get_current_user)):
    if current_user["role"] != "admin":
        raise HTTPException(403, "Admin access required")
    db.clear()
    return {"message": "Database cleared"}

Bonus — Flask Alternative & Deployment Tips

Flask is the traditional Python API framework — simpler setup, more manual control. Here's the equivalent Products API in Flask, plus deployment options for both frameworks:

Python — flask_api.py & deployment tips
# ── Flask equivalent — pip install flask ─────────────
from flask import Flask, jsonify, request, abort

app = Flask(__name__)
products: dict = {}

@app.get("/products")
def list_products():
    return jsonify(list(products.values()))

@app.post("/products")
def create_product():
    data = request.get_json()
    if not data or "name" not in data:
        abort(400, "name is required")
    import uuid
    pid  = str(uuid.uuid4())[:8]
    products[pid] = {"id": pid, **data}
    return jsonify(products[pid]), 201

@app.get("/products/<product_id>")
def get_product(product_id: str):
    p = products.get(product_id)
    if not p: abort(404)
    return jsonify(p)

# Run: flask --app flask_api run --debug

# ══════════════════════════════════════════════════════
# ── FastAPI vs Flask ──────────────────────────────────
# FastAPI:  automatic docs, Pydantic validation, async,
#           type hints, better performance
# Flask:    simpler, more flexible, huge ecosystem,
#           great for beginners and small APIs
# ══════════════════════════════════════════════════════

# ── Deployment options ────────────────────────────────

# 1. Local development
# uvicorn main:app --reload --host 0.0.0.0 --port 8000

# 2. Production (multiple workers)
# gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

# 3. Docker
# FROM python:3.12-slim
# WORKDIR /app
# COPY requirements.txt .
# RUN pip install -r requirements.txt
# COPY . .
# CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

# 4. Cloud platforms
# Render.com — free tier, automatic deploys from GitHub
# Railway.app — simple, fast deploys
# AWS Lambda — serverless via Mangum adapter
# Google Cloud Run — containerised, scales to zero

Practice Python Online — Free Compilers

FastAPI and Flask run best locally or on Replit (which supports web servers). Use Google Colab for learning Pydantic models and validation logic, or Replit for running a full API server.

▶
Online Python 3 Compiler
Write and test FastAPI/Flask code. For a running server, use Replit or a local environment.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Install FastAPI: pip install fastapi uvicorn. Run: uvicorn main:app --reload. Auto docs at /docs (Swagger) and /redoc.
  • Define endpoints with decorators: @app.get(), @app.post(), @app.put(), @app.patch(), @app.delete(). Path params in {braces}, query params as function args.
  • Pydantic BaseModel validates request bodies automatically. Use Field() for constraints. Set response_model= to shape output. Use model_dump(exclude_unset=True) for PATCH.
  • Raise HTTPException(status_code=404, detail="...") for errors. Use @app.exception_handler() for custom error formats. Add CORSMiddleware for frontend access.
  • JWT auth flow: POST /token → verify username/password → return JWT → client sends Authorization: Bearer {token} → Depends(get_current_user) verifies it.
  • Passwords: always hash with passlib (bcrypt). Never store or log plain-text passwords. Never use weak algorithms.
  • Flask alternative: simpler syntax, more manual, great for smaller APIs. Both can be deployed the same way — Render, Railway, Docker, AWS Lambda.
  • For production: add a real database (SQLite with SQLAlchemy, PostgreSQL), move secrets to environment variables, add request rate limiting, and write tests with pytest + httpx.
⚡
Free Resource
Download our Python REST API Cheat Sheet
FastAPI setup, CRUD endpoints, Pydantic, JWT auth, error handling, Flask comparison and deployment — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

response_model=Product does three things:

  • Filtering — only includes fields defined in the model. If your handler returns extra internal fields (like hashed_password), they're automatically excluded.
  • Validation — validates the response data before sending, catching bugs where handlers return wrong data shapes.
  • Documentation — FastAPI uses it to document the exact response schema in Swagger UI / OpenAPI spec.
✓ Answer

In PATCH, all fields are optional — the client only sends the fields they want to change. Without exclude_unset=True, model_dump() includes all fields with their defaults (including None), which would overwrite existing data with nulls.

# Client sends only {"price": 9.99}
data.model_dump()                  # {"price": 9.99, "name": None, ...}
data.model_dump(exclude_unset=True) # {"price": 9.99} ← correct!
✓ Answer

JSON Web Token (JWT) is a signed, base64-encoded string containing a payload (claims like username, role, expiry). It's stateless — the server doesn't need a session database to verify it, just the secret key.

Flow: client sends credentials → server verifies → server creates JWT signed with secret → client stores JWT → client sends it in Authorization: Bearer {token} header with every request → server decodes and verifies signature.

✓ Answer

PUT replaces the entire resource. The client must send all fields — any fields not sent are set to their defaults. It's idempotent: calling it multiple times with the same data gives the same result.

PATCH is a partial update — only the fields sent are updated. Missing fields keep their current values. Use PATCH when you want to update just one or two fields of a large object.

✓ Answer

Browsers enforce the Same-Origin Policy — JavaScript on frontend.com is blocked from making requests to api.backend.com unless the server explicitly allows it.

CORS (Cross-Origin Resource Sharing) is the mechanism that allows servers to opt-in. CORSMiddleware adds the necessary headers (Access-Control-Allow-Origin etc.) to responses. Without it, any browser-based frontend calling your API will get blocked.

In production, set allow_origins=["https://yourfrontend.com"] rather than "*".

MCQ 1 of 3
Which HTTP status code should a POST endpoint return when successfully creating a resource?
MCQ 2 of 3
In FastAPI, how do you declare that a function parameter should be extracted from the URL path?
MCQ 3 of 3
What FastAPI tool is used to inject dependencies like get_current_user into route handlers?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel