A backend is mostly a collection of routes: "when a POST arrives at /signup, run this code". In this chapter you'll learn every HTTP method you'll use, how to read data from the URL, how Express matches paths (including the changes in Express 5), and how to test your API with Postman.
In this chapter you'll learn
- the five main HTTP methods and how they map to CRUD
- how to write a route handler for each method
- route parameters (
req.params) and query strings (req.query) - Express path patterns: what changed between Express 4 and Express 5
- how to test APIs with Postman
Before you start: read Chapter S2 03: Creating our Express server. REST basics are in Chapter S2 02: Features, HLD LLD and Planning.
HTTP methods and CRUD
Each HTTP method expresses an intent. Together they cover the four CRUD operations from Chapter 13: Creating a database & mongodb:
| Method | CRUD | Has a body? | Example |
|---|---|---|---|
POST | Create | yes | create an account: POST /signup |
GET | Read | no | get a profile: GET /profile/view |
PUT | Update (replace) | yes | replace a whole user: PUT /users/42 |
PATCH | Update (partial) | yes | change only the bio: PATCH /profile/edit |
DELETE | Delete | usually no | delete a user: DELETE /users/42 |
PUT vs PATCH and idempotency are explained in Chapter S2 02: Features, HLD LLD and Planning.
Express has a function for each method:
const express = require("express");
const app = express();
app.get("/user", (req, res) => {
res.send({ firstName: "Akshay", lastName: "Saini" }); // objects are sent as JSON
});
app.post("/user", (req, res) => {
// save the user to the database (Season 2 chapters S2-06, S2-07)
res.send("User saved successfully");
});
app.patch("/user", (req, res) => {
res.send("User updated");
});
app.delete("/user", (req, res) => {
res.send("User deleted");
});
app.listen(3000);const express = require("express");
const app = express();
app.get("/user", (req, res) => {
res.send({ firstName: "Akshay", lastName: "Saini" }); // objects are sent as JSON
});
app.post("/user", (req, res) => {
// save the user to the database (Season 2 chapters S2-06, S2-07)
res.send("User saved successfully");
});
app.patch("/user", (req, res) => {
res.send("User updated");
});
app.delete("/user", (req, res) => {
res.send("User deleted");
});
app.listen(3000);Same path, four different handlers. Express picks one based on the method of the request.
Reading data from the request
A client can send data in three places. You'll use all three in DevTinder:
| Where | Looks like | Read it with | Typical use |
|---|---|---|---|
| Route parameter | /user/42 | req.params | identify which resource: an ID |
| Query string | /user/feed?page=2&limit=10 | req.query | optional filters, sorting, pagination |
| Body | JSON sent with POST/PATCH | req.body (needs express.json()) | the data itself: a signup form |
Route parameters: req.params
A path segment starting with : is a placeholder that matches any value:
app.get("/user/:userId", (req, res) => {
console.log(req.params); // { userId: "42" }
res.send(`You asked for user ${req.params.userId}`);
});
// several parameters
app.get("/user/:userId/:name", (req, res) => {
console.log(req.params); // { userId: "42", name: "akshay" }
res.send(req.params);
});app.get("/user/:userId", (req, res) => {
console.log(req.params); // { userId: "42" }
res.send(`You asked for user ${req.params.userId}`);
});
// several parameters
app.get("/user/:userId/:name", (req, res) => {
console.log(req.params); // { userId: "42", name: "akshay" }
res.send(req.params);
});Parameter values are always strings: "42", not 42. Convert them when you need a number: Number(req.params.userId).
You'll use this pattern in DevTinder's POST /request/send/:status/:toUserId (Chapter S2 12: Logical DB Query and Compound Indexes).
Query strings: req.query
Everything after ? in the URL is the query string: key=value pairs joined with &. Express parses it for you:
// GET /user/feed?page=2&limit=10
app.get("/user/feed", (req, res) => {
console.log(req.query); // { page: "2", limit: "10" } ← strings again
res.send(req.query);
});// GET /user/feed?page=2&limit=10
app.get("/user/feed", (req, res) => {
console.log(req.query); // { page: "2", limit: "10" } ← strings again
res.send(req.query);
});Query parameters don't change which route matches: /user/feed and /user/feed?page=2 both reach the same handler. You'll use them for pagination in Chapter S2 14: Building Feed API and Pagination.
The request body: req.body
The body arrives as raw text, in pieces. Express parses JSON bodies once you add its built-in middleware:
app.use(express.json()); // put this BEFORE your routes
app.post("/signup", (req, res) => {
console.log(req.body); // { firstName: "Akshay", emailId: "akshay@example.com", ... }
res.send("Received!");
});app.use(express.json()); // put this BEFORE your routes
app.post("/signup", (req, res) => {
console.log(req.body); // { firstName: "Akshay", emailId: "akshay@example.com", ... }
res.send("Received!");
});Without express.json(), req.body is undefined. Middleware is the topic of Chapter S2 05: Middlewares and Error Handlers; using req.body with a database comes in Chapter S2 07: Diving into APIs.
Path patterns: Express 4 vs Express 5
The lectures show special characters in route paths. These are Express 4 features. Since Express 5 (what npm install express gives you today) uses a stricter path syntax, it's worth seeing both:
| Pattern | In Express 4 | In Express 5 |
|---|---|---|
/ab+c | + = one or more b: matches /abc, /abbbc | crashes at startup: Unexpected + at index 3 |
/ab?c | ? = b is optional: matches /abc, /ac | crashes at startup: Unexpected ? at index 3 |
/a*cd | * = anything in between: /acd, /abcd, /axyzcd | no error, but now means /a + a wildcard named cd: it matches /abc and /a/b/c too |
/ab(cd)?e | groups | crashes at startup |
/user/:userId | parameter | parameter, unchanged ✅ |
/a/ (a real RegExp) | any path containing a | same ✅ |
The Express 5 way to write these:
// optional part: wrap it in braces
app.get("/ab{c}", handler); // matches /ab and /abc
app.get("/user{/:id}", handler); // /user and /user/42 (id is optional)
// wildcard: must have a name, and comes back as an ARRAY of path segments
app.get("/files/*filepath", (req, res) => {
console.log(req.params.filepath); // /files/a/b.txt → ["a", "b.txt"]
res.send("ok");
});
// need +, ? or * semantics? use a real regular expression
app.get(/^\/ab+c$/, handler); // /abc, /abbc, /abbbc...// optional part: wrap it in braces
app.get("/ab{c}", handler); // matches /ab and /abc
app.get("/user{/:id}", handler); // /user and /user/42 (id is optional)
// wildcard: must have a name, and comes back as an ARRAY of path segments
app.get("/files/*filepath", (req, res) => {
console.log(req.params.filepath); // /files/a/b.txt → ["a", "b.txt"]
res.send("ok");
});
// need +, ? or * semantics? use a real regular expression
app.get(/^\/ab+c$/, handler); // /abc, /abbc, /abbbc...In practice, real APIs rarely need these patterns: plain paths and :params cover almost everything.
If you follow the lectures with Express 4 (npm install express@4), the original patterns work. If you're on Express 5 and your server crashes at startup with TypeError: Unexpected ..., a route path with +, ?, ( or ) is the reason.
Multiple handlers for one route
You can pass more than one function to a route. Each one calls next() to hand over to the next. This is the first glimpse of middleware, covered fully in Chapter S2 05: Middlewares and Error Handlers:
app.get(
"/user",
(req, res, next) => {
console.log("Handler 1");
next(); // pass control to the next function
},
(req, res) => {
console.log("Handler 2");
res.send("Response from handler 2");
}
);app.get(
"/user",
(req, res, next) => {
console.log("Handler 1");
next(); // pass control to the next function
},
(req, res) => {
console.log("Handler 2");
res.send("Response from handler 2");
}
);Testing APIs with Postman
A browser address bar can only send GET requests. To test POST, PATCH and DELETE, use an API client:
- Postman: the most popular
- alternatives: Thunder Client (a VS Code extension), Insomnia, or
curlin the terminal
Testing a request in Postman:
- Create a new request; choose the method (POST) and enter the URL (
http://localhost:3000/signup). - For a body: Body → raw → JSON, then type the JSON (shown below the list). Choosing JSON also sets the
Content-Type: application/jsonheader, whichexpress.json()needs. - Click Send and read the status code, headers and body of the response.
- Save requests into a collection to reuse them later.
The JSON body for step 2:
{ "firstName": "Akshay", "emailId": "akshay@example.com" }{ "firstName": "Akshay", "emailId": "akshay@example.com" }The same request with curl:
curl -X POST http://localhost:3000/signup \
-H "Content-Type: application/json" \
-d '{"firstName":"Akshay","emailId":"akshay@example.com"}'curl -X POST http://localhost:3000/signup \
-H "Content-Type: application/json" \
-d '{"firstName":"Akshay","emailId":"akshay@example.com"}'Common mistakes
- Using
app.usefor endpoints: it answers every method and every sub-path (Chapter S2 03: Creating our Express server). - Treating params as numbers:
req.params.id === 42is always false; it's the string"42". - Sending a body with GET: many clients and proxies drop it. Use params or a query string.
- Forgetting
express.json(), or putting it after the routes:req.bodyisundefined. - Express 4 path patterns on Express 5: the server crashes on startup.
Key takeaways
- POST creates, GET reads, PUT replaces, PATCH partially updates, DELETE deletes.
app.get/post/patch/put/delete(path, handler)routes by method and path.- Data comes from
req.params(/user/:id),req.query(?page=2) andreq.body(needsexpress.json()). Params and query values are strings. - Express 5 removed
+,?,()in string paths; use{optional}, named wildcards (/*name) or real regular expressions. - Test non-GET routes with Postman (or curl).
Interview questions
Q1. What is the difference between req.params, req.query and req.body?
req.params holds route parameters from the path (/user/:id → { id: "42" }), used to identify a resource. req.query holds the parsed query string (?page=2 → { page: "2" }), used for optional filters and pagination. req.body holds the parsed request body (JSON from POST/PUT/PATCH), which requires body-parsing middleware like express.json().
Q2. What is routing in Express?
Routing decides which code handles a request, based on its HTTP method and path. In Express you define routes with app.METHOD(path, ...handlers) (or on a Router), and Express runs the first matching route's handlers in the order they were defined.
Q3. What changed about route paths in Express 5?
Express 5 upgraded its path-matching library: the characters ?, +, *, ( and ) are no longer special in string paths; using ?, +, ( or ) throws an error at startup. Wildcards must be named (/*splat) and their value is an array of segments, and optional parts use braces (/user{/:id}). Regular expression routes still work. Express 5 also forwards rejected promises from async handlers to the error handler automatically.
Q4. How do you handle a route that should work for every HTTP method?
Use app.all(path, handler) for an exact path, or app.use(path, fn) to also cover all sub-paths (typically for middleware). For example app.all("/secret", ...) runs for GET, POST, DELETE... on /secret only.
Q5. What is Postman used for?
Postman is an API client for building and sending HTTP requests with any method, headers, query parameters and body, and inspecting the responses (status, headers, body, timing). Teams use it to test and debug APIs, save requests in collections, use environment variables (like a base URL), and write automated tests.
Q6. Why are route parameters always strings?
They come from the URL, which is just text. Express doesn't know whether 42 is meant as a number, an ID or a name. Convert explicitly (Number(req.params.id)), and validate the value before using it, for example check that an ID is a valid MongoDB ObjectId.
What's next
You've used next() to chain two handlers. In Chapter S2 05: Middlewares and Error Handlers you'll learn the full idea behind it: middleware, the most important concept in Express, plus error handling and HTTP status codes.