
Engineering Tutorial · Beginner to Intermediate · Hands-on API Design
Your mobile app needs to browse books, place orders and track deliveries. What should the backend API look like—and what separates a working demo from a production-ready service? Follow Ananya (backend engineer), Maya (architect) and Ravi (SRE) as they build a fictional online bookstore API. This is a realistic teaching example, not a claim about a specific company’s architecture.
The visual story: a bookstore API from request to response
1. Start with a concrete user journey
A customer opens the bookstore, searches for a book, views its details, places an order and checks the order status. Ananya maps these actions to resource-oriented endpoints. Maya insists on stable contracts and correct HTTP semantics; Ravi asks what happens when a customer retries after a network timeout.
| User action | Endpoint | Expected behavior |
|---|---|---|
| Browse books | GET /v1/books?limit=20 | Paginated public catalog |
| View one book | GET /v1/books/{id} | 200 or 404 |
| Create order | POST /v1/orders | Authenticated; idempotency key |
| Check order | GET /v1/orders/{id} | Only the owning customer or authorized staff |
| Cancel eligible order | POST /v1/orders/{id}/cancel | Business transition, not arbitrary deletion |
2. Architecture: keep the first version simple
A sensible first production architecture is client → load balancer or API gateway → stateless API service → relational database, with optional Redis cache for hot catalog reads. Add a background queue for emails or fulfillment events when needed. Do not introduce microservices, Kafka or a service mesh simply because the product might grow someday.
Authentication verifies the caller; authorization checks whether the caller may access the specific order. TLS protects transport. An API gateway can apply coarse rate limits, but the application must still enforce resource-level permissions and validation.
3. Design predictable REST contracts
- Use plural nouns for resources:
/booksand/orders, not/getBooks. - Use
GETfor safe reads,POSTto create resources or perform non-idempotent commands,PUTfor full replacement where supported,PATCHfor partial updates, andDELETEwhen deletion is appropriate. - Return
201 Createdwith aLocationheader for a newly created order,400for malformed requests,401for unauthenticated callers,403for forbidden access,404for missing resources,409for state conflicts and429for rate limits. - Document request and response schemas with OpenAPI; use stable error codes and correlation IDs.
POST /v1/orders HTTP/1.1
Authorization: Bearer <access-token>
Idempotency-Key: checkout-8d12
Content-Type: application/json
{
"items": [{"book_id": "book_123", "quantity": 1}],
"shipping_address_id": "addr_456"
}
HTTP/1.1 201 Created
Location: /v1/orders/ord_789
Content-Type: application/json
{
"id": "ord_789",
"status": "pending",
"total_minor": 49900,
"currency": "INR"
}
Do not trust prices submitted by the client. Calculate totals server-side using catalog prices, applicable tax and promotions. Store money in integer minor units or an appropriate decimal representation—not binary floating point.
4. A runnable FastAPI starting point
The following minimal Python example demonstrates request validation, typed responses and pagination. It uses in-memory sample data; it is not a production deployment and deliberately omits persistence, authentication and ordering.
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel, Field
app = FastAPI(title="Bookstore API", version="1.0.0")
class Book(BaseModel):
id: str
title: str
price_minor: int = Field(ge=0)
currency: str = "INR"
BOOKS = [
Book(id="book_123", title="Distributed Systems", price_minor=49900),
Book(id="book_124", title="API Design", price_minor=29900),
]
@app.get("/v1/books", response_model=list[Book])
def list_books(limit: int = Query(default=20, ge=1, le=100),
offset: int = Query(default=0, ge=0)):
return BOOKS[offset:offset + limit]
@app.get("/v1/books/{book_id}", response_model=Book)
def get_book(book_id: str):
for book in BOOKS:
if book.id == book_id:
return book
raise HTTPException(status_code=404, detail="Book not found")
python -m venv .venv
# Activate the environment, then:
pip install fastapi uvicorn
uvicorn main:app --reload
# Visit http://127.0.0.1:8000/docs
Use --reload only for local development. For production, pin dependencies, run behind HTTPS and a supported ASGI process manager, and configure readiness checks, timeouts and resource limits.
5. Validation, authentication and authorization
Validate input at the boundary: field types, maximum lengths, allowed enumerations, positive quantities, permitted sort keys and request-body size. Use parameterized database queries. For identity, validate token signatures, issuer, audience, expiry and scopes using an established authentication library or identity provider. Never treat a user-supplied order owner ID as authorization.
def can_read_order(current_user_id: str, order: dict) -> bool:
return order["customer_id"] == current_user_id
# In an authenticated route, load the order by ID and check ownership.
# Return 404 or 403 according to your documented disclosure policy.
6. Idempotency: the checkout retry problem
Ravi simulates a timeout: the customer taps “Place order”, the server commits the order, but the response never reaches the phone. The phone retries. Without protection, the customer may create two orders. Require an Idempotency-Key for order creation, scope it to the authenticated customer and operation, persist a request fingerprint and completed response, and return the original result for a matching retry. Reject reuse of the same key with a different payload.
The key reservation, order creation and response record must be coordinated transactionally in the database. If two requests race, one should win the unique constraint while the other waits or receives a well-defined in-progress response. Set a documented key-retention window; do not assume an idempotency key prevents duplicates forever.
7. Pagination, caching and rate limiting
| Concern | Starting choice | When to revisit |
|---|---|---|
| Pagination | Limit + offset for a small catalog | Use cursor pagination for large, changing datasets |
| Caching | Cache public book details with TTL and invalidation | When stale prices or inventory affect decisions |
| Rate limits | Per-user and per-IP budgets with 429 | When tenant fairness or abuse patterns change |
| Database indexes | Index frequently filtered/sorted fields | Review query plans and slow queries |
| Timeouts | Bound external requests and DB calls | Tune from measured latency budgets |
Use ETags and conditional requests where they reduce bandwidth. Never serve another user’s private order data from a shared cache. Rate limits should return useful retry guidance, and clients should back off rather than retry aggressively.
8. Reliability and observability
- Log structured fields such as request ID, route template, tenant ID, status and duration, while redacting secrets and personal data.
- Instrument request rate, error rate and duration; distinguish expected 4xx responses from server failures.
- Use distributed traces across API, database and downstream calls, with sampling policies that protect privacy.
- Set timeouts, bounded retries with jitter and circuit breaking for unstable dependencies. Avoid retrying non-idempotent operations without protection.
- Deploy with health checks, backward-compatible migrations, rollout monitoring and rollback plans.
9. Testing strategy
| Layer | Example test |
|---|---|
| Unit | Price calculation and validation boundaries |
| API integration | POST order then GET order with authorized identity |
| Security | User A cannot access User B’s order |
| Contract | OpenAPI schema matches actual responses |
| Resilience | Timeout after commit then retry same idempotency key |
| Performance | p95 latency under realistic traffic and DB size |
A high-value failure test deliberately drops the response after a successful order commit and then repeats the request with the same key. Assert that the response is stable and exactly one logical order exists. This is stronger than simply checking a happy-path 201.
10. Production checklist
- OpenAPI documentation and consistent versioning policy.
- Input validation, authentication and object-level authorization.
- TLS, secrets management and secure database access.
- Idempotent order creation and safe payment integration.
- Pagination, indexes, bounded payloads and rate limiting.
- Structured logs, metrics, tracing and actionable alerts.
- Automated tests, safe schema migrations and rollback procedures.
Frequently asked questions
What is the difference between REST and HTTP?
HTTP is the application protocol; REST is an architectural style that uses resource-oriented representations, uniform interfaces and other constraints. Not every HTTP JSON endpoint is necessarily RESTful.
Should I use FastAPI, Django REST Framework, Spring Boot or Express?
Choose based on your team’s language, ecosystem, operational maturity and requirements. The architecture principles here apply across frameworks; FastAPI is simply a concise teaching example.
Is JWT always necessary?
No. Depending on the client and deployment, secure server-side sessions may be appropriate. Whatever mechanism you choose, validate identity and enforce authorization independently.
When should I split the API into microservices?
Usually after there is a concrete scaling, ownership or deployment boundary that justifies the additional distributed-system complexity. A modular monolith is often a strong starting point.
How can I avoid duplicate orders?
Use a client-supplied idempotency key and enforce it transactionally with a unique constraint and persisted result; also design downstream payment and fulfillment effects to be idempotent.
Interview challenge
Your bookstore receives 10,000 order submissions per minute during a sale. Payment processing occasionally times out after charging the customer. Design the idempotency, order state machine, reconciliation and observability needed to avoid double charging and lost orders.