Skills / Back-end development and APIs / Designing a REST API

Back-end development and APIs, lesson 2 of 8

Designing a REST API

A good API is predictable: once a developer understands one part, they can guess the rest. REST is the most common style for web APIs, and it is built around resources: the things your system deals with, such as users, orders and products.

Use nouns for paths, and methods for actions. Avoid paths like /getOrders or /deleteOrder?id=7. Instead:

  • GET /orders lists orders
  • POST /orders creates an order
  • GET /orders/7 reads order 7
  • PATCH /orders/7 changes part of order 7
  • DELETE /orders/7 removes it

Nest only for clear ownership: GET /orders/7/items lists the items of order 7.

Return honest status codes. Send 201 with the new resource after a create, 400 with a clear message when the input is wrong, 404 when something does not exist, and 401 or 403 for sign-in and permission problems. Never send 200 with an error hidden inside the body.

Make errors useful. A response like {"error": "quantity must be at least 1"} saves the next developer an hour.

Paginate lists. Never return a million rows at once: GET /orders?page=2&per_page=50.

Version from the start, for example /v1/orders, so you can improve the API later without breaking the apps that already use it.

Write the API down before you build it: a short list of paths, methods, inputs and responses. It is much cheaper to fix a design on paper than in code that people already depend on.

Try it: Design a small REST API for a library: list the paths and methods for books, borrowing a book and returning it, and the status code each should return on success.

Check yourself

1. Which is the better REST path for deleting order 7?

2. What status code should a successful create return?

3. Why put a version like /v1/ in your API paths?