Real-world Applications and Projects
Apply your knowledge in practical projects to build real-world applications using FastAPI.
Content
Developing an E-commerce Platform
Versions:
Watch & Learn
AI-discovered learning video
Build an E‑commerce Platform with FastAPI — Real-World Guide (No Fluff, Slightly Dramatic)
Hook: Imagine a customer clicks "Buy Now" and your API does three things perfectly: charge the card, reserve inventory, and send the confirmation email — all within a few hundred milliseconds and zero nerve-racking race conditions. That’s the day your FastAPI app stops being academic and starts being a real business.
This lesson assumes you already know how to build RESTful endpoints (see: Building a RESTful API) and how to use WebSockets for live updates (see: Creating a Chat Application). It also builds on Deployment Strategies — because once you’ve got orders flowing, you need them to survive spikes, DDoS, and your CFO’s optimism.
What this covers (quick map)
- Core architecture and components for an e‑commerce backend
- Data modeling patterns and example Pydantic schemas
- Critical features: cart, orders, payments, inventory, admin
- Background processing, Webhooks, and idempotency
- Scaling, caching, and deployment notes (K8s/Docker/managed services)
Why FastAPI fits e‑commerce
- Async by design for handling lots of I/O (DB, caches, payment gateways).
- Dependency injection gives clean, testable database/session patterns.
- Pydantic makes validation predictable — crucial for money and inventory.
E‑commerce is validation, idempotency, and orchestration. FastAPI helps with all three.
Architecture (high-level)
- Client (Web/mobile)
- API Gateway / FastAPI app
- Services:
- Relational DB (orders, products, users)
- Cache (Redis) for sessions, carts, rate limits
- Background worker (Celery/RQ/fastapi BackgroundTasks)
- Object store (S3) for images
- Payment gateway (Stripe/PayPal) via secure webhooks
- Search engine (Elasticsearch/Opensearch)
Database choice (quick comparison)
| Need | Good fit | Why |
|---|---|---|
| Strong transactions, complex joins | PostgreSQL | ACID, foreign keys, JSONB for flexible metadata |
| Schemaless catalogs, fast iteration | MongoDB | Flexible product attributes, but weaker transactions |
| Fast ephemeral state (carts, sessions) | Redis | In‑memory, TTLs, Pub/Sub |
Data models — small taste (Pydantic + SQLAlchemy)
from pydantic import BaseModel, condecimal
from typing import List
class ProductOut(BaseModel):
id: int
name: str
price: condecimal(decimal_places=2, gt=0)
in_stock: int
class CartItem(BaseModel):
product_id: int
qty: int
class OrderCreate(BaseModel):
items: List[CartItem]
shipping_address_id: int
payment_method: str
Use SQLAlchemy/asyncpg for DB interactions; keep Pydantic models for validation/response.
Essential Endpoints (MVP)
- GET /products?search= & /products/{id}
- POST /cart (or use Redis session)
- POST /orders (create & charge)
- POST /webhooks/payments (idempotent)
- GET /orders/{id}/status (optionally via WebSocket for live updates)
Example: create order with background tasks
from fastapi import BackgroundTasks, APIRouter, Depends
router = APIRouter()
@router.post('/orders')
async def create_order(order: OrderCreate, background_tasks: BackgroundTasks, db=Depends(get_db), user=Depends(get_current_user)):
# 1. validate stock (DB transaction)
# 2. create order row with status="pending"
# 3. enqueue background task to process payment and finalize
background_tasks.add_task(process_payment_and_finalize, order_id)
return {'order_id': order_id, 'status': 'processing'}
Use DB transactions to reserve inventory before charging to avoid oversell.
Payments & Webhooks — the real fun
- Never store raw card data. Use Stripe/PayPal tokens.
- Use idempotency keys for payment endpoints (client adds unique key). That prevents double-charges when retries happen.
- Webhooks must be verified (signature check) and implemented idempotently: webhook event -> find order by external_id -> if already handled, ack.
@router.post('/webhooks/stripe')
async def stripe_webhook(payload: dict):
event_id = payload['id']
if webhook_already_processed(event_id):
return {'status': 'ok'}
# handle event
Background workers & async orchestration
Use Celery/RQ or a cloud task queue for heavy-lift jobs: sending emails, resizing images, fulfillment calls, analytics. For light-duty tasks, FastAPI's BackgroundTasks is fine — but don't use it for tasks that must survive process restarts.
Patterns to avoid: charging in the HTTP request thread; long waits on external APIs.
Live updates: WebSockets for order status
Borrow the WebSocket patterns you learned in the Chat Application: push order updates (shipping stages) to connected clients. Use Redis Pub/Sub to broadcast across multiple FastAPI instances.
Caching, Search, and Performance hacks
- Cache product pages and categories in CDN + Redis.
- Use Elastic/Opensearch for faceted search — avoid heavy SQL LIKE queries.
- Rate limit critical endpoints (checkout, login) via Redis-based rate limiter.
- Use connection pooling for DB and asyncpg for Postgres.
Security & Compliance (short but not optional)
- HTTPS everywhere (TLS termination at load balancer)
- Use JWT + refresh tokens for customer sessions or cookie sessions with secure flags.
- PCI: outsource card storage to Stripe/Adyen; your API should only handle tokens.
- Validate inputs (Pydantic), sanitize outputs, limit file uploads, and monitor for fraud (velocity checks).
Security is not a feature: it's the baseline. No one remembers a store for "we implemented secure headers", but they remember charged cards twice.
Testing, CI/CD, Observability
- Unit test Pydantic validation and business logic.
- Integration tests hitting a test DB and a mock payment gateway.
- E2E tests for checkout flows (Selenium/Playwright).
- Use structured logging (JSON) and traces (OpenTelemetry). Monitor key metrics: order rate, failure rate, payment success rate, latency percentiles.
For deployment, reuse your Deployment Strategies knowledge: containerize your app, use managed DB, autoscale worker pools, and prefer rolling updates with health checks.
MVP Roadmap (prioritized)
- Product catalog + search
- Auth (JWT) + user profiles
- Cart + orders (DB transactions) — local payments mocked
- Payment gateway integration + webhook handling
- Admin panel + inventory management
- Background jobs + email confirmations
- Monitoring, caching, and scaling
Final pep talk (and checklist)
- Start small: perfect order flow > fancy UI.
- Make every external call idempotent and observable.
- Treat inventory as a shared resource — always reserve in DB transactions.
- Outsource sensitive things (card storage) to specialists.
Bold takeaway: FastAPI gives you the speed and safety to build an e‑commerce backend that scales — but you still have to design for idempotency, observability, and race conditions.
Go build something that charges correctly on the first try and ships on the second. Your future self (and your customers) will thank you.
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!