Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 77 ยท REST APIs

API Design, Versioning and CORS

Design a clean HTTP API in Django: resource URLs, idempotent methods, filtering, sorting, pagination, URL versioning, bearer tokens and a CORS middleware.

The previous lesson showed how to return JSON from plain Django views. Making an API work is the easy part. Making it predictable is harder: clients you have never met will depend on your URLs, your status codes and your field names, and every change risks breaking one of them.

This lesson is about the conventions that make an API pleasant to use and safe to evolve. You will design resource URLs, understand which methods are idempotent, add filtering, sorting and pagination, version your API, protect it with bearer tokens and let browsers on other origins call it through CORS headers. Everything runs live with the Django test client.

Resource-oriented URLs

A REST-style API models resources (things) and lets HTTP methods express the action. URLs name nouns, not verbs.

Goal Poor design Better design
List products GET /getProducts/ GET /products/
Read one product GET /product_detail?id=7 GET /products/7/
Create a product POST /createProduct/ POST /products/
Replace a product POST /updateProduct/7/ PUT /products/7/
Partially update POST /updateProductPrice/7/ PATCH /products/7/
Delete a product GET /deleteProduct/7/ DELETE /products/7/

A few habits keep URLs tidy:

  • Use plural nouns for collections (/products/) and the identifier for one member (/products/7/).
  • Nest only when ownership is obvious: /authors/3/books/ is fine, but stop after one level of nesting. Deeper paths are awkward to build and to cache.
  • Keep URLs lowercase and stable. Names that appear in URLs are part of your public promise.
  • Use query strings for optional refinements of a collection (filter, sort, page), never for choosing the resource itself.
flowchart LR
    C["Client"] -->|"GET /products/"| L["Collection<br/>list"]
    C -->|"POST /products/"| L
    C -->|"GET /products/7/"| M["Member<br/>one product"]
    C -->|"PUT, PATCH, DELETE<br/>/products/7/"| M

A collection URL supports listing and creating; a member URL supports reading, replacing, updating and deleting.

Idempotency and safe methods

Networks fail. A client that sends a request and never sees the response will retry, and your API must cope. Two properties describe how methods behave under retries:

  • A safe method does not change server state (GET, HEAD, OPTIONS).
  • An idempotent method has the same effect whether you call it once or ten times (GET, PUT, DELETE, plus the safe ones).

POST is neither: sending the same POST twice usually creates two records. PUT replaces the whole resource with the body you send, so repeating it leaves the same final state. DELETE is idempotent even though the response may differ: the first call removes the row, and a repeat finds nothing to remove. Most APIs still answer 204 No Content both times, since the client's goal ("this product should not exist") is satisfied.

Idempotency is why GET must never delete or modify anything: browsers, proxies and crawlers freely retry and prefetch GET requests.

Filtering, sorting and pagination

Collections grow, so list endpoints need three conventions from day one:

  • Filtering with named query parameters: ?category=home.
  • Sorting with a sort parameter and a leading minus for descending order: ?sort=-price.
  • Pagination so one response never contains ten thousand rows: ?limit=20&offset=40 (or a page number, or an opaque cursor).

Two rules matter for safety. First, whitelist the fields clients may sort by, otherwise a request such as ?sort=password may leak information through ordering. Second, cap the page size so a client cannot ask for limit=10000000.

Python A product collection with filter, sort and pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the two PUT lines: the first creates the product (201 Created) and the second replaces it with identical data (200 OK), and the row count does not change. Both DELETE calls end in the same state. That is idempotency in action.

Offset pagination (limit and offset) is simple but gets slow on huge tables and can skip or repeat rows when data changes between requests. For feeds with millions of rows, prefer cursor pagination: return an opaque token that encodes the last row seen, and filter with id__gt on the next call. For most APIs, offset pagination is perfectly fine. See QuerySets for slicing and ordering.

Status codes that clients can rely on

Choose codes by meaning and use them consistently:

  • 200 OK for a successful read or update, 201 Created after a create (ideally with a Location header), 204 No Content when there is nothing to return.
  • 400 Bad Request for malformed input, 422 Unprocessable Content if you want to separate "valid syntax, invalid meaning" (pick one convention and keep it).
  • 401 Unauthorized when credentials are missing or wrong, 403 Forbidden when the user is known but not allowed, 404 Not Found for a missing resource.
  • 405 Method Not Allowed with an Allow header, 409 Conflict for state clashes such as a duplicate unique value, 429 Too Many Requests for rate limiting.

Return errors in one shape everywhere, for example {"error": "message"} or a dictionary of field errors, so client code can handle failures without special cases.

Versioning

Once clients depend on your API, you cannot change a response shape freely. Versioning lets old and new shapes coexist. The most common and simplest strategy is a version in the URL: /api/v1/... and /api/v2/.... It is visible in logs, easy to cache and easy to test with a browser. Alternatives are a version in a header (Accept: application/vnd.example.v2+json) or a query parameter; they keep URLs clean but are harder to debug.

Some guidance for a healthy versioning life:

  • Additive changes are not breaking. Adding a new field to a response is safe, so you rarely need a new version for it. Renaming or removing a field, changing a type, or tightening validation is breaking.
  • Keep the number of live versions small, announce deprecations early, and use the Deprecation and Sunset response headers to tell clients.
  • Share code between versions. Only the serialization layer usually differs, so keep the business logic in one place.

Django's URL namespaces (see URL Routing) fit versioning well: include one URL module per version under a version prefix.

Token authentication

Browsers get a session cookie after login (see Sessions and Cookies). API clients such as mobile apps and scripts usually send a bearer token in the Authorization header instead:

TEXT
Authorization: Bearer 9f8c1e...

The server looks the token up, finds the user it belongs to and handles the request on that user's behalf. A good token scheme follows a few rules:

  • Generate tokens with a cryptographically secure source (secrets.token_urlsafe()), never from user data.
  • Store only a hash of each token in the database, as you would a password, so a database leak does not expose working credentials.
  • Let users create several tokens and revoke each one, ideally with an expiry date.
  • Send tokens only over HTTPS. Reply 401 with a WWW-Authenticate: Bearer header when authentication fails.

The next example puts versioning and token checking together with a tiny decorator.

CORS: letting browsers call your API

Browsers apply the same-origin policy: JavaScript loaded from https://app.example.com may not read responses from https://api.example.com unless the API opts in. The opt-in mechanism is CORS (Cross-Origin Resource Sharing), a set of response headers.

For simple requests the browser sends an Origin header and checks the answer's Access-Control-Allow-Origin. For requests that use methods like PUT or DELETE, or custom headers like Authorization, the browser first sends a preflight: an OPTIONS request that asks permission. Your server must answer it with the allowed methods and headers.

sequenceDiagram
    participant B as Browser (app.example.com)
    participant A as API (api.example.com)
    B->>A: OPTIONS /profile/ (Origin, Access-Control-Request-Method: PUT)
    A-->>B: 204 + Allow-Origin, Allow-Methods, Allow-Headers
    B->>A: PUT /profile/ (Origin, Authorization)
    A-->>B: 200 + Allow-Origin

The preflight asks permission; only if the headers allow it does the browser send the real request.

Three CORS mistakes are worth avoiding. Never echo any Origin back blindly: check it against an allow-list. Never combine a wildcard * with credentials. And add Vary: Origin whenever the answer depends on the origin, so caches do not serve one origin's headers to another. In production most teams use the well-maintained django-cors-headers package, but writing the middleware yourself shows exactly what it does.

Python Versioned URLs, bearer tokens and a CORS middleware

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice two things. The CORS middleware answers the preflight itself, before the view and before token checking, because browsers never attach credentials to a preflight. And the evil origin gets a normal response without the Access-Control-Allow-Origin header, so the browser refuses to hand the data to that site's JavaScript. CORS is enforced by browsers; it does not stop curl or a server-side script, which is why you still need real authentication.

CORS is not a security feature for your server. It only controls what browser JavaScript from other sites may read. Always authenticate and authorize every request on the server, whatever the CORS headers say.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL and method best express 'delete product 7' in a resource-oriented API?

    Resources are nouns in the URL and the HTTP method carries the action. DELETE on the member URL is the conventional design, and GET must never change data.
  2. 2. A client sends the same PUT request to /products/20/ three times. What is the expected result?

    PUT is idempotent: it replaces the resource with the body you send, so repeating it does not change the outcome. POST is the method that usually creates a new record each time.
  3. 3. Why should an API whitelist the fields clients may sort by?

    Passing user input straight into order_by lets clients probe fields you never meant to expose and can force slow queries. A small allow-list keeps sorting safe and predictable.
  4. 4. What does a CORS preflight request look like?

    Before sending a request with a method such as PUT or a header such as Authorization, the browser asks permission with an OPTIONS request. The server answers with the allowed methods and headers.
  5. 5. Which change is usually safe to make inside an existing API version?

    Clients normally ignore fields they do not know, so adding fields is non-breaking. Renaming, removing or retyping fields breaks existing clients and calls for a new version.

Summary

  • Model resources as plural nouns (/products/, /products/7/) and let HTTP methods express actions.
  • GET, PUT and DELETE are idempotent, POST is not; retries are why this matters.
  • Offer filtering, whitelisted sorting and capped pagination on every list endpoint, and keep error responses in one shape.
  • Put the version in the URL (/api/v1/) and treat renaming, removing or retyping fields as breaking changes.
  • Bearer tokens in the Authorization header suit API clients; store hashes, allow revocation and use HTTPS.
  • CORS is a browser-enforced opt-in: answer preflights, check origins against an allow-list, send Vary: Origin, and still authenticate on the server.

Next lesson: Django REST Framework Overview.