REST Principles

What is REST?

REST (REpresentational State Transfer) is a style for designing web APIs. An API that follows it is called RESTful. The key rules:

  • Resources: everything is a resource (product, order, user) identified by a URL.
  • Use nouns, not verbs: the HTTP method is the verb. GET /api/products, not /api/getProducts.
  • Representations: the client gets a representation of the resource, usually JSON.
  • Stateless: each request carries everything the server needs (e.g. the token). The server does not remember the previous request.
  • Uniform interface: the same methods and status codes mean the same thing everywhere.

Good vs Bad URL Design

GoalBadGood (RESTful)
list productsGET /getAllProductsGET /api/products
one productGET /product?id=5GET /api/products/5
create productPOST /createProductPOST /api/products
delete productGET /deleteProduct/5DELETE /api/products/5
orders of a userGET /getOrdersByUser?u=3GET /api/users/3/orders
filter / sortGET /productsCheapElectronicsGET /api/products?category=electronics&sort=price

Tip: Use plural nouns (/products), lowercase with hyphens (/order-items), and a version prefix when needed (/api/v1/products).

Practice

Exercise: Design RESTful endpoints (method + URL) for ShopEase categories: list all, get one, create, rename, delete, and list the products of one category.

Show answer
GET    /api/categories
GET    /api/categories/{id}
POST   /api/categories
PUT    /api/categories/{id}        (or PATCH to change only the name)
DELETE /api/categories/{id}
GET    /api/categories/{id}/products