1. REST Principles

REST stands for Representational State Transfer. It's an architectural style โ€” a set of rules for how clients and servers communicate over HTTP. When an API follows these rules consistently, it's called a RESTful API.

REST was defined by Roy Fielding in his 2000 doctoral dissertation, and it became the dominant style for web APIs because it maps naturally to HTTP. Every API you'll ever consume โ€” Stripe, Twilio, GitHub, Shopify โ€” is a REST API.

๐Ÿ›’
UrbanCart Context
Why REST matters for UrbanCart

UrbanCart has a React frontend, a Node/Express backend, and a mobile app in the works. All three need to talk to the same data. A well-designed REST API means the React app, mobile app, and any future partners can all use the same endpoints with predictable, consistent behavior.

The four principles you need to know:

๐ŸŒ

Stateless

Each request must contain everything needed to understand it. The server stores no client session state. If you need authentication, send the token with every request โ€” the server doesn't remember your previous request.

๐Ÿ“ฆ

Resource-Based URLs

A URL identifies a thing (a resource), not an action. /products identifies the products collection. /products/42 identifies product 42. The URL is a noun, not a verb.

๐Ÿ”„

Uniform Interface

HTTP verbs define the action. GET, POST, PUT, PATCH, DELETE mean the same thing across every resource. You don't invent new verbs โ€” you combine existing verbs with resource URLs.

๐Ÿงฉ

Client-Server Separation

The frontend and backend are independent. The React app doesn't know how the database works. The API doesn't know how the UI renders data. Either side can change without breaking the other, as long as the API contract stays the same.

REST Request/Response Cycle
Client
React / Mobile
โ†’
HTTP Request
verb + URL + body
โ†’
Express API
Node.js server
โ†’
JSON Response
status + data

2. Resource Naming

The URL is the public face of your API. Good resource naming makes an API intuitive โ€” a developer can guess the right endpoint without reading documentation.

Nouns, not verbs

The single most common REST mistake is putting verbs in URLs. The HTTP method already expresses the action. The URL should express the resource.

โŒ

Wrong โ€” Verb in URL

/getProducts
/createProduct
/deleteProduct?id=5
/updateProductPrice

โœ…

Correct โ€” Noun URL + HTTP verb

GET /products
POST /products
DELETE /products/5
PATCH /products/5

Additional naming rules

  • Plural nouns โ€” use /products, not /product. The collection is plural even when you access a single item (/products/42).
  • Lowercase โ€” URLs are case-sensitive on most servers. Always lowercase to avoid confusion.
  • Hyphens for multi-word โ€” use /product-reviews not /productReviews or /product_reviews. Hyphens are URL-safe and readable.
  • Hierarchy for relationships โ€” nested resources reflect ownership. /products/42/reviews means "reviews belonging to product 42."
  • No trailing slash โ€” /products is correct; /products/ is not.
UrbanCart URL structure: /api/products โ†’ product collection. /api/products/42 โ†’ single product. /api/products/42/reviews โ†’ reviews for that product. The /api prefix distinguishes API routes from page routes.
routes/products.js UrbanCart REST URL structure

3. HTTP Methods

HTTP gives you five verbs that map directly to the four CRUD operations. Choosing the right verb matters โ€” clients, caches, and proxies treat them differently based on their semantic meaning.

Method CRUD UrbanCart Example Idempotent?
GET Read Fetch product list or a single product Yes โ€” safe to repeat
POST Create Add a new product to the catalogue No โ€” creates a new resource each time
PUT Replace Replace all fields of product 42 Yes โ€” same result every time
PATCH Partial update Update only the price of product 42 Usually yes
DELETE Delete Remove product 42 from the catalogue Yes โ€” deleting twice has the same result
PUT vs PATCH: PUT replaces the entire resource โ€” if you omit a field, it gets wiped. PATCH sends only the fields you want to change. In practice, most APIs only implement PATCH for updates because it's safer and more efficient. UrbanCart uses PATCH.
routes/products.js HTTP methods in Express

4. HTTP Status Codes

Status codes tell the client what happened. A proper REST API never returns 200 OK with an error inside the body โ€” the status code itself should be meaningful. Clients write their error handling based on these codes.

Code Name When to use in UrbanCart
200 OK OK Successful GET, PATCH, DELETE with a response body
201 Created Created POST created a new product; include the new resource in the response
400 Bad Request Bad Request Malformed JSON, missing required fields, invalid data types
401 Unauthorized Unauthorized No auth token provided, or token is invalid/expired
403 Forbidden Forbidden Token is valid, but this user doesn't have permission (non-admin tries to delete a product)
404 Not Found Not Found GET /api/products/9999 where product doesn't exist
422 Unprocessable Entity Unprocessable Entity Request body is valid JSON but fails validation rules (price < 0, name is empty string)
500 Internal Server Error Internal Server Error Database connection dropped, unhandled exception โ€” something broke on our side
401 vs 403: 401 means "I don't know who you are โ€” please send credentials." 403 means "I know who you are, but you're not allowed to do this." An unauthenticated request gets 401. An authenticated customer trying to delete a product gets 403.
routes/products.js Status codes in practice

5. Request Validation

Validation is the gatekeeper of your API. Every POST and PATCH request needs validation before you touch the database. Without it, you'll store garbage data, crash on null values, or open security holes.

Good validation does three things:

  1. Checks presence โ€” required fields must exist and not be empty strings.
  2. Checks types and ranges โ€” price must be a number and must be non-negative; name must be a string under 200 characters.
  3. Returns specific errors โ€” tell the client exactly what's wrong, not just "bad request."
middleware/validateProduct.js Validation middleware for UrbanCart products
Example validation error response โ€” POST /api/products with bad data
HTTP/1.1 422 Unprocessable Entity Content-Type: application/json { "error": "Validation failed", "details": [ { "field": "name", "message": "Name is required" }, { "field": "price", "message": "Price must be non-negative" } ] }
Best practice: Return all validation errors at once, not one at a time. Nothing is more frustrating as a developer than fixing one error, resubmitting, and getting a different error. Show them everything that's wrong in one response.
routes/products.js Using the validation middleware

6. Pagination

UrbanCart has thousands of products. Returning all of them in one request would be slow, expensive, and unusable in the UI. Pagination splits the results into pages, letting clients request exactly what they need.

The industry-standard approach uses query string parameters: ?page=1&limit=10. The response includes metadata so the client knows how many total results exist and how many pages there are.

routes/products.js Pagination with page + limit
GET /api/products?page=1&limit=10 GET
curl "http://localhost:3000/api/products?page=1&limit=10"
{ "data": [ { "id": 1, "name": "Wireless Headphones", "price": 49.99, "category": "audio", "stock": 120 }, { "id": 2, "name": "USB-C Hub 7-in-1", "price": 29.99, "category": "accessories", "stock": 85 }, { "id": 3, "name": "Laptop Stand Pro", "price": 39.99, "category": "accessories", "stock": 200 }, { "id": 4, "name": "Mechanical Keyboard", "price": 89.99, "category": "peripherals", "stock": 45 }, { "id": 5, "name": "4K Webcam", "price": 69.99, "category": "peripherals", "stock": 60 }, { "id": 6, "name": "LED Desk Lamp", "price": 24.99, "category": "lighting", "stock": 300 }, { "id": 7, "name": "Ergonomic Mouse", "price": 34.99, "category": "peripherals", "stock": 90 }, { "id": 8, "name": "Monitor Arm", "price": 59.99, "category": "accessories", "stock": 55 }, { "id": 9, "name": "Portable SSD 1TB", "price": 79.99, "category": "storage", "stock": 40 }, { "id": 10,"name": "Phone Stand", "price": 14.99, "category": "accessories", "stock": 500 } ], "total": 42, "page": 1, "limit": 10, "pages": 5 }
Always include pagination metadata. The client needs to know: how many total items are there? how many pages? what page am I on? Without this, the frontend can't render pagination controls. The format above โ€” data, total, page, limit, pages โ€” is the standard shape used by most production APIs.

7. Filtering & Sorting

Pagination controls how many results you get. Filtering and sorting control which results you get, and in what order. Both use query string parameters, and both work on top of pagination.

routes/products.js Filtering and sorting
GET /api/products?category=audio&sort=price&order=asc&page=1&limit=10 GET
curl "http://localhost:3000/api/products?category=audio&sort=price&order=asc&page=1&limit=10"
{ "data": [ { "id": 1, "name": "Wireless Earbuds", "price": 29.99, "category": "audio", "stock": 200 }, { "id": 7, "name": "Portable Speaker", "price": 44.99, "category": "audio", "stock": 75 }, { "id": 1, "name": "Wireless Headphones", "price": 49.99, "category": "audio", "stock": 120 }, { "id": 12, "name": "Noise-Cancel Headset", "price": 79.99, "category": "audio", "stock": 30 } ], "total": 4, "page": 1, "limit": 10, "pages": 1 }
Whitelist your sort fields. Never pass req.query.sort directly to your database query โ€” it's a SQL/NoSQL injection risk. Always check that the value is in an approved list of column names before using it.

8. Complete CRUD API โ€” UrbanCart Products

Let's put it all together. The full UrbanCart Products API has 7 endpoints covering every operation a client might need. Below is the complete implementation followed by curl examples for each endpoint.

routes/products.js Complete UrbanCart Products API โ€” all 7 endpoints

Live API examples with curl

GET /api/products?page=1&limit=10&category=audio&sort=price GET
curl "http://localhost:3000/api/products?page=1&limit=10&category=audio&sort=price"
{ "data": [ { "id": 1, "name": "Wireless Earbuds", "price": 29.99, "category": "audio", "stock": 200 }, { "id": 7, "name": "Portable Speaker", "price": 44.99, "category": "audio", "stock": 75 }, { "id": 2, "name": "Wireless Headphones", "price": 49.99, "category": "audio", "stock": 120 } ], "total": 3, "page": 1, "limit": 10, "pages": 1 }
GET /api/products/:id GET
curl "http://localhost:3000/api/products/2"
{ "data": { "id": 2, "name": "Wireless Headphones", "price": 49.99, "category": "audio", "description": "Noise-cancelling, 30hr battery, Bluetooth 5.3", "stock": 120, "createdAt": "2026-04-10T09:15:00.000Z" } }
POST /api/products โ€” Create a new product POST
curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -d '{ "name": "4K Webcam Pro", "price": 69.99, "category": "peripherals", "description": "4K 30fps, built-in ring light, auto-focus", "stock": 60 }'
HTTP/1.1 201 Created { "data": { "id": 43, "name": "4K Webcam Pro", "price": 69.99, "category": "peripherals", "description": "4K 30fps, built-in ring light, auto-focus", "stock": 60, "createdAt": "2026-04-18T14:22:31.000Z" } }
PATCH /api/products/:id โ€” Update price and stock only PATCH
curl -X PATCH http://localhost:3000/api/products/43 \ -H "Content-Type: application/json" \ -d '{ "price": 64.99, "stock": 80 }'
HTTP/1.1 200 OK { "data": { "id": 43, "name": "4K Webcam Pro", "price": 64.99, "category": "peripherals", "description": "4K 30fps, built-in ring light, auto-focus", "stock": 80, "createdAt": "2026-04-18T14:22:31.000Z" } }
DELETE /api/products/:id DELETE
curl -X DELETE http://localhost:3000/api/products/43
HTTP/1.1 200 OK { "message": "Product 43 deleted" }
POST /api/products โ€” Validation error example POST
curl -X POST http://localhost:3000/api/products \ -H "Content-Type: application/json" \ -d '{ "price": -5 }'
HTTP/1.1 400 Bad Request { "error": "name, price, and category are required" } # If name and category are present but price is -5: HTTP/1.1 422 Unprocessable Entity { "error": "price must be a non-negative number" }
Mount the router in app.js: All these endpoints become available once you add app.use('/api/products', require('./routes/products')); to your Express app. The router handles everything under that prefix automatically.

Quiz

Question 1 of 5
What does REST stand for?
Question 2 of 5
Which HTTP method should be used to partially update a resource?
Question 3 of 5
What status code should a successful resource creation return?
Question 4 of 5
Which URL follows REST naming conventions?
Question 5 of 5
What is pagination used for in APIs?
0
/ 5
Great job!

You completed the REST API Design quiz.

Next Lesson

Database Integration (PostgreSQL) โ†’
You've designed your API. Now connect it to a real PostgreSQL database.
Africa & India's Best AI Academy
๐Ÿค– AI-first ๐ŸŽ“ Placement Assistance

You just designed a production-grade REST API.
Now build a full-stack career that scales.

Join the Best AI Programs โ€” three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses โ†’