Design a REST API for an online bookstore
Design the REST API for an online bookstore: customers browse and search books, read reviews, manage a cart and place orders; admins manage the catalog.
A typical framing: "Mobile and web clients and some partner integrations will use this API. Walk me through the resources and endpoints, what requests and responses look like, how you handle errors, pagination and versioning, and how you keep it safe to retry."
TL;DR
Model the domain as resources (nouns) and use HTTP methods for actions: GET /books, POST /orders, PATCH /orders/{id}. Nest only where ownership is real (/books/{id}/reviews), and keep URLs shallow. Return the right status codes (201 with Location on create, 404, 409 for conflicts, 422 for validation errors) and one consistent error format (RFC 9457 problem details).
Lists use cursor pagination, with filtering and sorting through query parameters. Writes that create something (orders, payments) accept an Idempotency-Key so retries don't create duplicates. Updates use ETag + If-Match to prevent lost updates. Version with a URL prefix (/v1) and evolve additively. Authenticate with OAuth2/JWT, authorize per resource, and rate-limit with standard headers.
1. Requirements
Questions worth asking:
- Who are the clients: our own web and mobile apps, third parties, both?
- Which flows matter most: browsing (read-heavy) or ordering (must be correct)?
- Do clients need real-time updates (order status), or is polling or webhooks enough?
- Expected scale and latency targets?
Functional
- Browse, search and filter books; view a book with its author and reviews.
- Write reviews (one per customer per book).
- Manage a cart, place an order, see order history and status.
- Admins create and update books and stock.
Non-functional
- Predictable, consistent conventions so clients can be written once.
- Safe retries on flaky mobile networks.
- Backward compatibility: old app versions keep working.
- Secure: customers only see their own carts and orders.
2. Entities and resources
Money is stored as integer minor units (priceCents) plus a currency, never floats. OrderItem copies the price at purchase time, because the book's price can change later.
3. API
| Method and path | Purpose | Success |
|---|---|---|
GET /v1/books?q=&authorId=&sort=-rating&limit=20&cursor= | Search and list | 200 |
GET /v1/books/{id} | One book | 200 |
POST /v1/books | Create (admin) | 201 + Location |
PATCH /v1/books/{id} | Partial update (admin) | 200 |
GET /v1/books/{id}/reviews | Reviews of a book | 200 |
POST /v1/books/{id}/reviews | Write a review | 201, 409 if one exists |
GET /v1/cart / PUT /v1/cart/items/{bookId} | The current user's cart | 200 |
POST /v1/orders | Place an order from the cart | 201 |
GET /v1/orders?status=shipped | My orders | 200 |
POST /v1/orders/{id}/cancel | Cancel (an action, not a field edit) | 200, 409 if already shipped |
Some actions don't map cleanly to CRUD, like canceling an order: it has rules and side effects (refund, restock). A sub-resource action such as POST /orders/{id}/cancel is clearer than PATCH { status: "canceled" }.
A list response:
{
"data": [
{
"id": "bk_81",
"title": "Designing Data-Intensive Applications",
"priceCents": 4999,
"currency": "USD"
}
],
"nextCursor": "eyJyYXRpbmciOjQuOSwiaWQiOiJia184MSJ9",
"hasMore": true
}An error response (application/problem+json):
{
"type": "https://api.bookstore.example/errors/insufficient-stock",
"title": "Not enough stock",
"status": 409,
"detail": "Only 2 copies of bk_81 are left.",
"errors": [{ "field": "items[0].quantity", "code": "max_exceeded" }]
}4. Core logic
Pagination
Offset pagination (?page=40) is simple but gets slow on deep pages (the database still scans the skipped rows) and skips or duplicates items when rows are inserted between requests. Cursor pagination encodes the last item's sort key and id, and the next query continues from there:
SELECT * FROM books
WHERE (rating, id) < (:lastRating, :lastId)
ORDER BY rating DESC, id DESC
LIMIT 21; -- one extra row tells us whether there's a next pageThe cursor is opaque (base64) so clients don't depend on its contents, and the id tie-breaker keeps the order stable.
Idempotent order creation
async function createOrder(req: Request) {
const key = req.headers.get('Idempotency-Key')
if (!key) return problem(400, 'missing-idempotency-key')
const saved = await idempotency.find(req.userId, key)
if (saved) {
// Same key with a different body is a client bug, not a retry.
if (saved.requestHash !== hash(req.body)) return problem(422, 'idempotency-key-reused')
return saved.response
}
const response = await db.transaction(async (tx) => {
const order = await orders.createFromCart(tx, req.userId) // reserves stock
const res = { status: 201, body: order, headers: { Location: `/v1/orders/${order.id}` } }
await idempotency.save(tx, req.userId, key, hash(req.body), res)
return res
})
return response
}Saving the response in the same transaction as the order means a crash can't leave an order without its key, or the other way round.
Concurrency on updates
Two admins edit the same book. Without protection, the last write silently wins. Return an ETag (a version) with every GET, require If-Match on PATCH, and answer 412 Precondition Failed when the version moved on.
5. Edge cases and extensions
- Versioning:
/v1in the path is the most visible and cache-friendly. Within a version, only make additive changes (new optional fields, new endpoints). Clients must ignore unknown fields. Breaking changes go to/v2, with aDeprecationandSunsetheader on the old one. - Auth: OAuth2 access tokens (JWT) for apps, scoped API keys for partners. Authorization is checked per resource:
GET /orders/{id}for someone else's order returns404(not403), so ids can't be probed. - Rate limiting:
429withRetry-After, plusRateLimit-*headers so clients can slow down before hitting it. - Caching:
Cache-ControlandETagon public reads like books; never cache cart or order responses in shared caches. - Over- and under-fetching: sparse fields (
?fields=id,title) and embedding (?include=author) avoid many round trips without switching to GraphQL. - Long operations (bulk import): return
202 Acceptedwith a job resource to poll, or send a webhook when done. - Documentation: an OpenAPI spec as the contract, used for docs, client generation and contract tests.
Common follow-ups
- "REST vs. GraphQL vs. gRPC?" REST for public, cacheable, resource-shaped APIs. GraphQL when many clients need different shapes of deeply related data. gRPC for internal service-to-service calls with strict schemas and streaming.
- "
PUTvs.PATCH?"PUTreplaces the whole resource and is idempotent by definition;PATCHchanges some fields. UsePATCHwith JSON Merge Patch for partial updates. - "How do you handle stock when two people buy the last copy?" A conditional update (
UPDATE books SET stock = stock - 1 WHERE id = ? AND stock >= 1) inside the order transaction; if no row changed, return409.
What interviewers look for
- Resource modeling with consistent naming, and sensible handling of actions that aren't CRUD.
- Correct status codes and one error format.
- Cursor pagination and why offset breaks down.
- Idempotency keys and optimistic concurrency (
ETag/If-Match). - Versioning, auth per resource, rate limiting and caching.