Designing a REST API

Resources, URLs and methods — design APIs that other developers find obvious to use.

Module 4: REST APIs · Lesson 11 of 26 · 15 min read · Free

REST is a set of conventions for designing APIs around resources (things: students, orders, products) and HTTP methods (actions). When you follow it, other developers can guess how your API works.

REST routes for a resource

The conventions

  • Nouns, plural, in paths: /api/students, /api/orders — not /api/getStudents or /api/createOrder. The method is the verb.
  • Ids in the path for one item: /api/students/3.
  • Query strings for filtering, sorting and paging: /api/students?className=SS2&sort=score&page=2.
  • Nested resources for things that belong to something: /api/orders/1/items, /api/users/7/orders.
  • JSON in and out, camelCase property names.
  • Status codes that mean something (lesson 3.1).
  • A version in the path once you have outside users: /api/v1/... — so you can change things later without breaking their apps.

Actions that aren't simple CRUD

Sometimes an action doesn't fit create/read/update/delete. Model it as a change to a sub-resource or a field:

  • Change order status: PATCH /api/orders/1/status with { "status": "delivered" }.
  • Cancel: POST /api/orders/1/cancel is also widely accepted.

Design before you code

Write the API down first — a table of method, path, request body, response and errors. The project brief for this course is exactly that. Front-end and mobile developers can start building against it while you build the back end.

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. Which is the RESTful path to get the student with id 3?

    • A GET /api/students/3
    • B GET /api/getStudent?id=3
    • C POST /api/students/get/3
    • D GET /api/student-3
    Show the answer

    A) GET /api/students/3 — Plural resource plus id in the path.

  2. Where should filters like className=SS2 go?

    • A In the query string
    • B In the path as /api/SS2/students only
    • C In the request body of a GET
    • D In a header
    Show the answer

    A) In the query string — Query strings filter, sort and page collections.

  3. Why put a version like /api/v1/ in public APIs?

    • A So you can make breaking changes later without breaking existing apps
    • B It's faster
    • C Browsers require it
    • D To hide the API
    Show the answer

    A) So you can make breaking changes later without breaking existing apps — v2 can change while v1 keeps working.

More free lessons: What the back end does · Install Node.js and use the terminal · Asynchronous code: promises and async/await · HTTP: requests, responses and status codes · Designing tables and relationships · Storing passwords safely · Automated tests and project structure