Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 72 ยท REST APIs

Designing a REST API

Design a clean REST API in Flask. Learn resources and URLs, HTTP verbs, idempotency, PUT vs PATCH, pagination, filtering, sorting and API versioning.

You can turn any Flask view into a JSON endpoint, but a handful of endpoints is not yet an API. An API that other people build on must be predictable: URLs that look alike for similar things, verbs that mean the same everywhere, lists that do not fall over when they get large, and a way to change things without breaking old clients.

REST is a set of conventions for exactly that, built on how HTTP already works. This lesson is about design rather than libraries. You will learn to model resources, map them to URLs and verbs, understand which operations are safe to repeat, paginate and filter lists, and version the API. Every idea is shown with a small runnable Flask app.

Resources, not actions

REST thinks in resources (things) and uses HTTP verbs for the actions. A URL names a thing, with a plural noun for a collection and an id for one member.

flowchart LR
    C["/api/v1/books<br/>the collection"] --> I["/api/v1/books/7<br/>one book"]
    I --> N["/api/v1/books/7/reviews<br/>a nested collection"]

Collections are plural nouns; an id picks one member; nesting expresses ownership.

Compare these two designs for the same feature:

Action-style (avoid) Resource-style (prefer)
POST /createBook POST /books
GET /getBook?id=7 GET /books/7
POST /deleteBook/7 DELETE /books/7
POST /books/7/updateTitle PATCH /books/7

Keep URLs lowercase, plural and shallow. Nesting more than two levels (/authors/3/books/7/reviews/9) is a sign that /reviews/9 would do. A few real actions do not fit a noun (for example POST /books/7/publish); that is acceptable when the verb is a genuine state change, but try the noun first.

The verbs and what they promise

Verb Meaning Safe? Idempotent? Typical success
GET Read yes yes 200
POST Create (or run an action) no no 201 + Location
PUT Replace the whole resource no yes 200 or 204
PATCH Change some fields no usually not guaranteed 200
DELETE Remove no yes 204

Safe means the request does not change anything on the server, so browsers, caches and crawlers may repeat it freely. Idempotent means doing it ten times has the same effect as doing it once. That matters in the real world: a mobile app on a bad network will retry a request if it never saw the answer. A retried PUT or DELETE is harmless; a retried POST could create a duplicate.

The difference between PUT and PATCH: PUT /books/7 carries the complete new representation and replaces the old one; PATCH /books/7 carries only the fields to change.

Python A complete resource: CRUD with the right verbs

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.

Run it and watch the idempotency: the second DELETE returns 404 instead of 204. The state of the server is identical after one or ten deletes (the book is gone), which is what idempotent means. Some APIs return 204 even for an already-deleted item; both choices are defensible, but be consistent.

Making POST safe to retry

Because POST is not idempotent, large APIs let clients send an Idempotency-Key header: the server remembers the key and, if it sees the same key again, returns the first result instead of creating a second record.

Python An Idempotency-Key for POST

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.

The retry gets the original order back (marked replayed) instead of a new one, so the keyed pair created only one order. The request without a key is a fresh order, which is why the store ends with two. Real services also expire old keys and compare the request body to the stored one, but the core idea is this small.

Pagination

A collection endpoint that returns every row works on your laptop and dies in production. Always paginate lists. The two common styles:

  • Page-based (offset): ?page=3&per_page=20. Simple, lets users jump to any page, but gets slow on huge tables and can show duplicates if rows are inserted while someone pages.
  • Cursor-based: ?after=<id>&limit=20. The client asks for "the 20 items after this one". It stays fast and stable for large or fast-changing data, but cannot jump to page 50.

Whichever you choose: set a sensible default, cap the maximum (per_page=100000 should not be allowed), and return the totals and navigation hints in the body so clients do not build URLs by guessing.

flowchart LR
    A["GET /api/items?page=2&per_page=10"] --> B["validate and clamp<br/>page, per_page"]
    B --> C["filter, then sort"]
    C --> D["slice: offset = (page - 1) * per_page"]
    D --> E["items + total + next/prev links"]

The order matters: filter first, then sort, then slice, and compute the total from the filtered data.

Filtering and sorting

Use query parameters for anything that narrows or orders a collection: ?kind=theory, ?author=Ada, ?sort=-year (a leading minus for descending is a popular convention). Only allow fields you list explicitly. Passing a client-chosen column name straight into a database query is a classic way to leak data or break things (see Web Security Essentials).

Python Paginate, filter and sort a collection

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 what the code defends against: a page of 0 or a negative number is clamped, per_page=500 is cut to the maximum, a non-numeric value falls back to the default thanks to type=int, and an unknown sort field gets a 400 with the allowed list. Never trust query parameters.

Versioning

Sooner or later you will need to change the shape of a response. If existing clients depend on the old shape, changing it breaks them. Versioning lets old and new live side by side. The simplest and most visible way is a version in the URL path: /api/v1/..., /api/v2/.... Blueprints (see Blueprints) fit this perfectly: one blueprint per version, each with its own url_prefix.

Other schemes exist (a custom header, or a media type such as application/vnd.example.v2+json). They keep URLs clean but are harder to try in a browser and to cache. For most projects, path versioning wins on clarity.

Only a breaking change needs a new version. Adding a new optional field or a new endpoint is backwards compatible. Removing or renaming a field, changing a type, or tightening validation is breaking.

Python Two versions side by side with blueprints

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.

When you retire a version, announce it in advance. Many APIs add Deprecation and Sunset response headers to old versions so client developers get a machine-readable warning.

A checklist for your own API

  • Plural nouns for collections; ids for members; at most two levels of nesting.
  • The verb carries the action: GET reads, POST creates, PUT replaces, PATCH edits, DELETE removes.
  • Correct status codes, as in Building JSON APIs, and one consistent error format.
  • Every list is paginated, with a default, a maximum and navigation links.
  • Filters and sort fields come from an allow-list.
  • Breaking changes go into a new version.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which URL and verb is the best REST design for deleting the book with id 7?

    The URL names the resource (/books/7) and the HTTP verb DELETE carries the action. GET must never change data.
  2. 2. What does it mean that DELETE and PUT are idempotent?

    Idempotency is about the resulting state. That is why clients can safely retry a PUT or DELETE after a network timeout, but must be careful with POST.
  3. 3. A client sends PATCH /books/7 with the body {"year": 1966}. What should happen?

    PATCH sends a partial update. Replacing the whole resource is the job of PUT.
  4. 4. Why should a list endpoint enforce a maximum per_page value?

    Without a cap, one request such as per_page=1000000 can load an entire table into memory. Clamp every client-supplied number.
  5. 5. Which change to an existing response requires a new API version?

    Renaming or removing a field breaks clients that depend on it. Additions are backwards compatible.

Summary

  • Model your API as resources: plural-noun collections, ids for members, verbs for actions.
  • GET is safe; GET, PUT and DELETE are idempotent; POST is neither, so use an Idempotency-Key when retries matter.
  • PUT replaces the whole resource, PATCH changes some fields.
  • Paginate every collection (page-based or cursor-based), clamp user-supplied numbers and return total and next/prev links.
  • Filter and sort only on an allow-list of fields.
  • Put the version in the URL (one blueprint per version) and bump it only for breaking changes.

Next, organize your endpoints as classes with Class-Based Views and MethodView.