Careeroza
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
| Goal | Bad | Good (RESTful) |
|---|---|---|
| list products | GET /getAllProducts | GET /api/products |
| one product | GET /product?id=5 | GET /api/products/5 |
| create product | POST /createProduct | POST /api/products |
| delete product | GET /deleteProduct/5 | DELETE /api/products/5 |
| orders of a user | GET /getOrdersByUser?u=3 | GET /api/users/3/orders |
| filter / sort | GET /productsCheapElectronics | GET /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