Part 3 of 9 · 2 min read
Resources and URLs
How REST names things, and how to read a URL.
Think of a library. Each book has a shelf code. A reader asks for a book by its code, not by describing a walk through the building.
REST names things in the same way. The server holds resources, and each has an address.
Resource
A resource is a thing the API talks about, such as a product, an order or a list of orders. It has a stable address, a URL.
Example: the product with identifier 42 lives at /products/42.
A URL has parts. Take https://www.example.com/products?sort=price.
httpsis the protocol.www.example.comis the host name./productsis the name of the resource, here a whole collection. With the host, it is the endpoint.?sort=priceis the query string. It adds options, here a sort order.
REST
REST is a set of conventions for HTTP APIs. Resources have URLs, the HTTP method says the action, and each request carries everything the server needs.
Example: GET /products/42 asks for product 42. No earlier request is needed to understand it.
The book "Understanding Distributed Systems" points out that nothing forces this style. A name such as /getProducts works, but then the list can no longer be cached by its URL. Following the convention keeps the caches (Level 3) and other tools useful.
Relations show up in the path. A product is a member of the collection, so it is /products/42. Its reviews are /products/42/reviews. The same book advises keeping URLs simple: if a path grows several levels deep, it is better to let the client make two requests than to build a long path.
A resource is sent as a representation, usually JSON.
{ "id": 42, "category": "Laptop", "price": 999 }
A few naming habits help.
- Use nouns in the plural for collections:
/orders, not/getOrders. - Put the action in the method, not in the path.
- Use one style of letters, for example lower case with hyphens.
- Keep identifiers in the path and options in the query string.
Common mistake
Naming endpoints after verbs, such as /createOrder and /deleteOrder. The method already says create or delete. Verb paths also make it hard to cache and hard to guess the next endpoint.
Check yourself:
- In
/shops/7/orders/90, what is the collection, and what is the single resource? - Why might a path with five nested levels be a poor design?