Objectives and prerequisites
By the end of this course, you will be able to design a readable REST API, choose methods and status codes, validate input, paginate, secure and evolve the contract without breaking clients. The common thread is the Mdjad catalogue API, consumed by a website and a mobile app.
Prerequisites: know HTTP, JSON and the basics of a web framework (courses F04 and F08). Examples use HTTP/1.1 and HTTP/2, JSON, OpenAPI 3.1 and curl commands. The concepts apply to Symfony, Laravel, Node or any other server.
Path: chapters 1 to 4 establish resources, URIs, methods and representations; chapters 5 to 7 cover validation, pagination and security; chapters 8 to 10 cover caching, contract and synthesis.
Convention: examples use https://api.mdjad.test, a fictional domain. Tokens are fictional. Any real API must use HTTPS, server-side secrets and logs without sensitive data.
1. Resources, representations and REST constraints
A REST API exposes resources: products, orders, customers. A resource is identified by a URI and represented in a format, often JSON. The client manipulates representations, not internal objects. The server remains free to choose its storage.
REST is not a protocol but a set of constraints: uniform interface, statelessness between requests, cache, layered system, optional code on demand. Statelessness means each request carries enough information to be understood, usually a token and parameters.
GET /v1/products/42 HTTP/1.1
Host: api.mdjad.test
Accept: application/json
Authorization: Bearer <fictional-token>
HTTP/1.1 200 OK
Content-Type: application/json
{"id":42,"name":"A5 Notebook","price_cents":350,"currency":"EUR"}
A REST API need not be perfect. A pragmatic API may have a few action routes, but it must remain predictable. Naming, statuses and errors matter more than theoretical purity. A client must be able to guess behaviour without reading server code.
Distinguish resource and collection. /products is a collection; /products/42 is an item. A sub-collection such as /orders/7/lines expresses ownership. Avoid URIs that mix an action and a resource: /getProduct?id=42 is less clear than /products/42.
Finally, a representation may include links. self, next, prev and links to relations help the client navigate. Links do not replace a clear contract, but they reduce coupling to hand-built URIs.
2. Designing URIs and versioning
A URI must be stable, readable and resource-oriented. Use plural nouns for collections, identifiers in the path for items, and lowercase with hyphens. Avoid verbs in the path when the HTTP method already carries the meaning.
GET /v1/products
GET /v1/products/42
GET /v1/products/42/reviews
POST /v1/products/42/reviews
GET /v1/orders?status=paid&limit=20
DELETE /v1/orders/7
Query parameters filter, sort or paginate a collection. They must not change the resource itself. ?category=stationery&sort=-price is a filter; ?action=delete is a disguised action. Prefer an explicit method and resource.
Version from the first external client. URI versioning — /v1/ — is simple and visible. Media-type versioning — Accept: application/vnd.mdjad.v2+json — is more principled but harder to operate. Choose a strategy and document it.
A new version should not be created for every compatible change. Adding an optional field is compatible; removing or renaming a field is not. Incompatible changes require a new version or a transition period with both formats.
Finally, plan deprecation. The Deprecation and Sunset headers indicate that a version is disappearing. Documentation, a changelog and a deadline are better than a sudden removal. Clients need time to migrate.
3. Methods, statuses and idempotency
HTTP methods have meaning: GET reads, POST creates or triggers, PUT replaces, PATCH partially modifies, DELETE removes. GET, PUT and DELETE must be idempotent: repeating the request produces the same final state.
POST /v1/orders HTTP/1.1
Content-Type: application/json
Idempotency-Key: 7c9e6679-7425-40de-944b-e07fc1f90ae7
{"product_id":42,"quantity":2}
HTTP/1.1 201 Created
Location: /v1/orders/1234
Content-Type: application/json
{"id":1234,"status":"pending","total_cents":700}
Use statuses precisely. 200 for success with a body, 201 for creation with Location, 204 for success without a body, 400 for an invalid request, 401 for missing or invalid authentication, 403 for a denied right, 404 for a missing resource, 409 for a conflict, 422 for business validation, 429 for rate limiting, 500 for a server error.
Do not return 200 with {"error": ...}: clients and proxies will not see the failure. Do not return 500 for a validation error: that is a client error. A wrong status complicates monitoring, retries and correction.
For creation, an idempotency key prevents duplicates if the client retries after a timeout. The server stores the key and result for a defined period. The same key with a different body must return a conflict, not create a second order.
Finally, HEAD returns headers without a body and OPTIONS describes allowed methods. These methods help clients and proxies. A 405 Method Not Allowed response must include the Allow header.
4. JSON representations and formats
Stable JSON uses consistent field names, predictable types and ISO 8601 dates with a timezone. Amounts are integer cents, never floats. Identifiers are strings or integers, but not both across routes.
{
"id": 42,
"name": "A5 Notebook",
"price_cents": 350,
"currency": "EUR",
"category": "stationery",
"created_at": "2026-10-23T09:00:00+03:00",
"links": {
"self": "/v1/products/42",
"reviews": "/v1/products/42/reviews"
}
}
Do not mix units. price without a unit is ambiguous; price_cents and currency are explicit. For dates, state the timezone or use UTC. For booleans, use true/false, not 0/1 or "yes".
An absent field and a null field have different meanings. Document them. A partial update with PATCH must distinguish "do not change" from "set to null". JSON Merge Patch or an explicit format avoids ambiguity.
Media types describe the format. Content-Type: application/json for a request, Accept: application/json for a response. For an error, application/problem+json. For a file, the real MIME type. Do not return HTML when the client expects JSON.
Finally, do not leak internal details. A password_hash field, a database identifier or an SQL trace has no place in a public response. Build an explicit representation instead of serialising the whole entity. This protects data and stabilises the contract.
5. Validation and actionable errors
Validate input early: type, format, length, range, ownership, consistency. Client-side validation improves experience but does not protect the server. Every rule must be checked server-side, with a message that helps the client correct.
HTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{
"type": "https://api.mdjad.test/problems/validation",
"title": "Validation failed",
"status": 422,
"detail": "The request contains invalid fields.",
"instance": "/v1/orders",
"errors": [
{"field": "quantity", "code": "min", "message": "Must be at least 1."}
]
}
The Problem Details format (RFC 9457) provides type, title, status, detail and instance. Add per-field errors without exposing internal details. The client can display a message and point to the faulty field.
Distinguish 400 — malformed request, invalid JSON — from 422 — valid JSON but a violated business rule. Some teams use 400 for both; choose a convention and document it. Consistency beats a theoretical debate.
Do not reveal the existence of a resource to an unauthorised user. A 403 response can confirm that a resource exists; a 404 may be safer. The decision depends on the threat model. Log the denial server-side, not in the response.
Finally, server errors must carry a correlation identifier. The client receives a generic message and a trace_id; logs contain the details. This supports diagnosis without disclosing sensitive data.
6. Pagination, filters and sorting
A collection can be large. Always paginate exposed lists. Offset pagination — ?page=2&limit=20 or ?offset=40&limit=20 — is simple but unstable if items are added or removed between pages. Cursor pagination is more stable for a stream.
GET /v1/products?category=stationery&sort=-price&limit=20&cursor=eyJpZCI6NDJ9
HTTP/1.1 200 OK
{
"data": [{"id":42,"name":"A5 Notebook","price_cents":350}],
"page": {"next_cursor": "eyJpZCI6NDF9", "has_more": true}
}
A cursor encodes a position, not an arbitrary page. It must be opaque to the client and signed or validated to prevent injection. The server decides order and maximum size. limit must have an upper bound.
Filters must be documented and combinable. ?status=paid&created_after=2026-01-01 is clearer than a home-grown query language. For complex needs, an explicit filter language may be justified, but it must be validated and limited.
Sorting follows a convention: sort=price ascending, sort=-price descending. Limit sortable fields to avoid expensive queries. Sorting on an unindexed field can bring down the database on a large collection.
Finally, an empty collection is not an error: return 200 with an empty array and pagination metadata. An out-of-range page may return 200 with an empty array or 400 if the cursor is invalid. Document the behaviour.
7. Authentication, authorisation and secrets
Authentication identifies the client; authorisation decides what it may do. A Bearer token in the Authorization header is common for an API. A secure session cookie suits a first-party web application. Do not mix the two without reason.
GET /v1/orders/1234 HTTP/1.1
Host: api.mdjad.test
Authorization: Bearer <fictional-token>
HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
{"type":"https://api.mdjad.test/problems/forbidden","title":"Forbidden","status":403}
A token must have a short lifetime, an audience and limited scopes. An administration token must not be used by a public client. Tokens are revoked, logged and never placed in a URL, where they end up in logs and history.
Authorisation happens server-side, from the authenticated identity. Do not trust a user_id supplied in the request body. Verify that the resource belongs to the current client. This prevents IDOR.
OAuth 2.0 and OpenID Connect describe delegated flows. For an internal API, a service token with scopes may suffice. For a third-party application, use a standard authorisation flow, not a shared password. Do not build your own token protocol.
Finally, server secrets — database key, signing key, OAuth secret — stay in a vault or a protected file. Public keys and client identifiers are not secrets. A committed or logged secret must be revoked and replaced.
8. Caching, ETag and rate limiting
Caching reduces load and latency. Cache-Control states duration and scope. For a rarely changed public resource, public, max-age=60 is reasonable. For a personalised response, private and a short duration. Never cache a response containing another user's data.
GET /v1/products/42 HTTP/1.1
If-None-Match: "a1b2c3"
HTTP/1.1 304 Not Modified
ETag: "a1b2c3"
Cache-Control: public, max-age=60
An ETag identifies a representation version. The client sends If-None-Match; if the version has not changed, the server returns 304 without a body. This saves bandwidth. An ETag must change when the representation changes, not on every request.
Last-Modified and If-Modified-Since offer a similar, less precise mechanism. For concurrent writes, If-Match with an ETag prevents overwriting a recent modification: the server returns 412 Precondition Failed if the version changed.
Rate limiting protects the service. Return 429 Too Many Requests with Retry-After. Limits must be documented and adapted to scopes. A client must handle 429 with a delay, not retry immediately in a loop.
Finally, caching and rate limiting depend on infrastructure: CDN, reverse proxy, application. Test the real headers, not only the code. A proxy can add or remove a header. Document the chain and verify that no private response is publicly cached.
9. OpenAPI contract, tests and evolution
OpenAPI describes routes, parameters, bodies, responses and schemas. A published contract lets clients generate code, test and detect breaks. Documentation must be versioned with the code, not written by hand in another tool.
openapi: 3.1.0
info:
title: Mdjad Catalogue API
version: 1.0.0
paths:
/v1/products/{id}:
get:
parameters:
- name: id
in: path
required: true
schema: { type: integer }
responses:
'200':
description: Product found
content:
application/json:
schema:
$ref: '#/components/schemas/Product'
'404':
description: Product not found
A contract test verifies that the implementation follows the schema: statuses, required fields, types, formats. It can generate requests from the contract or validate real responses. An untested contract drifts quickly.
API tests cover nominal cases, errors, authorisation, pagination and limits. They use an isolated database and test tokens. A test that depends on a real user or an external quota is fragile.
Evolution follows a rule: compatible first, deprecation next, removal last. Add fields, keep old ones, document the removal date. A client must not discover a break in production. The changelog is part of the product.
Finally, measure version and field usage. A field nobody uses can be removed; a field used by a critical client must be kept. Without measurement, deprecation becomes guesswork. Logs must respect privacy.
10. Synthesis: designing the catalogue API
The catalogue API exposes /v1/products, /v1/products/{id}, /v1/categories and /v1/orders. Reads are public or authenticated depending on context; writes require a token and scopes. Responses are JSON, errors are Problem Details.
GET /v1/products?category=stationery&limit=20 HTTP/1.1
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=60
ETag: "catalogue-20261023"
{"data":[{"id":42,"name":"A5 Notebook","price_cents":350}],"page":{"has_more":false}}
Decisions are documented: URI versioning, cursor pagination, amounts in cents, RFC 9457 errors, ETag on detail pages, rate limiting per token. Each decision has a reason and a consequence for clients.
Security is built in: HTTPS, short tokens, scopes, ownership checks, server validation, logs without secrets. Errors do not disclose the existence of an unauthorised resource. Rate limits return 429 with a delay.
The OpenAPI contract is versioned and tested. Tests cover statuses, schemas, authorisation and pagination. A break is preceded by deprecation and a transition period. Clients have a changelog.
Finally, a successful API is predictable, documented and observable. Metrics track latency, errors by status, 429 rate and version usage. An API is not just a set of routes: it is a durable contract with clients.
Exercise 1 — Name the resources
Propose URIs to list products, read one product, list its reviews and create a review. Why avoid /getProducts?
Solution
GET /v1/products, GET /v1/products/{id}, GET /v1/products/{id}/reviews, POST /v1/products/{id}/reviews. /getProducts puts a verb in the URI and duplicates the meaning of GET; it makes caching, statuses and documentation less natural.
Exercise 2 — Choose statuses
Which statuses for: successful creation, invalid field, missing resource, denied right, exceeded rate? Justify.
Solution
Creation: 201 with Location. Invalid field: 422 (or 400 by convention). Missing resource: 404. Denied right: 403. Exceeded rate: 429 with Retry-After. The status must reflect the cause so the client can react.
Exercise 3 — Problem Details error
Write a 422 response for a quantity below 1, with a faulty field and a message. Which media type do you use?
Solution
Use Content-Type: application/problem+json with type, title, status: 422, detail, instance and an errors array containing field: quantity, code: min, message. The client can display the message and point to the field without parsing a free string.
Exercise 4 — Pagination
A collection of 10,000 products must be paginated. Compare offset and cursor. Why bound limit?
Solution
Offset is simple but unstable when items are added or removed. A cursor encodes a position and remains stable for a stream. Bounding limit protects the database and bandwidth; without a bound, a client can request 100,000 items and bring down the service.
Exercise 5 — Authorisation
A client calls GET /v1/orders/1234 with a valid token, but the order belongs to another client. What do you return and what do you log?
Solution
Return 403 or 404 depending on the disclosure policy, with a Problem Details error containing no order data. Log server-side the identity, requested identifier, time and decision. Never return another client's order content.
Exercise 6 — ETag and cache
A product page changes rarely. How do you use ETag and Cache-Control? What happens if the client sends a stale ETag?
Solution
The server returns an ETag for the representation and Cache-Control: public, max-age=60. The client sends If-None-Match; if it matches, the server returns 304 without a body. If stale, it returns 200 with the new representation and a new ETag. For concurrent writes, If-Match can return 412.
Capstone — catalogue API
Design and document an API for products, categories and orders: URIs, methods, statuses, JSON schemas, errors, pagination, authentication, caching and versioning. Deliver an OpenAPI contract, six request/response examples and a note on decisions and limits.
Grading: consistent resources and URIs; correct methods and statuses; server validation; Problem Details errors; bounded pagination; per-resource authorisation; cache and ETag; tested contract; documented deprecation; no sensitive data exposed.
Common mistakes and diagnostic method
Classic mistakes: returning 200 with an error, using 500 for validation, exposing the whole entity, accepting a user_id from the body, paginating without a bound, putting a token in the URL, caching a private response, and breaking a field without a new version.
Method: reproduce with curl -i, read the status and headers, check the body and correlation logs, then isolate the layer. A cache problem shows in headers; an authorisation problem shows in identity and resource. Add a contract test after every fix.
Self-assessment
You must be able to explain resource and representation, design URIs, choose methods and statuses, validate and structure errors, paginate, secure, use ETag and evolve a contract.
Self-assessment: I can justify 201 and Location; I can distinguish 401 and 403; I can explain idempotency; I can refuse access to another client's resource. To go further, study OAuth 2.0, OpenAPI and contract testing.
References
- RFC 9110 — HTTP Semantics, accessed 23 October 2026.
- RFC 9457 — Problem Details for HTTP APIs, accessed 23 October 2026.
- OpenAPI Specification 3.1, accessed 23 October 2026.
- OWASP — API Security Top 10, accessed 23 October 2026.
- OAuth 2.0, accessed 23 October 2026.