Introduction
When developing APIs or working with web servers in Node.js, understanding HTTP methods is crucial. These methods define the type of action that should be performed on a given resource. Whether you’re retrieving data, creating a new user, or updating a profile, each action corresponds to a specific HTTP method.
This blog post will explore the most commonly used HTTP methods in Node.js, their purpose, and how they are implemented using the Express.js framework.
What Are HTTP Methods?
HTTP methods, also known as verbs, specify the desired action to be performed on a resource. Each method has a distinct purpose, and knowing when to use which method is key to building efficient and REST-compliant APIs.
List of HTTP Methods
Here’s a quick overview of the most important HTTP methods:
Method | Description | Safe? | Idempotent? |
---|---|---|---|
GET | Retrieve resources | ✅ Yes | ✅ Yes |
HEAD | Retrieve headers for a resource | ✅ Yes | ✅ Yes |
OPTIONS | Get allowed methods for a resource | ✅ Yes | ✅ Yes |
POST | Create new resources | ❌ No | ❌ No |
PUT | Update/replace an entire resource | ❌ No | ✅ Yes |
PATCH | Partially update a resource | ❌ No | ❌ No |
DELETE | Delete a resource | ❌ No | ✅ Yes |
Detailed Explanation of Each Method
1. GET
- Purpose: Used to retrieve data from a server.
- Safe & Idempotent: Yes.
- Example: Fetch all users from an API.
Code Example (Node.js/Express)
const express = require('express');
const app = express();
app.get('/users', (req, res) => {
res.send('List of all users');
});
app.listen(3000, () => console.log('Server running on port 3000'));
2. POST
- Purpose: Used to create a new resource on the server.
- Safe & Idempotent: No (can create multiple records if repeated).
- Example: Create a new user in the database.
Code Example (Node.js/Express)
app.post('/users', (req, res) => {
const newUser = req.body;
res.send(`User created: ${newUser.name}`);
});
Note: To access req.body
, you’ll need a body parser middleware (express.json()
).
3. PUT
- Purpose: Used to update an entire resource.
- Safe & Idempotent: Idempotent but not safe.
- Example: Update user information.
Code Example (Node.js/Express)
app.put('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedUser = req.body;
res.send(`User with ID ${userId} updated`);
});
Note: PUT replaces the entire resource. If you’re updating only a few fields, use PATCH.
4. PATCH
- Purpose: Partially update a resource.
- Safe & Idempotent: Not idempotent or safe.
- Example: Update only the email of a user.
Code Example (Node.js/Express)
app.patch('/users/:id', (req, res) => {
const userId = req.params.id;
const updatedData = req.body;
res.send(`User with ID ${userId} partially updated`);
});
Note: PATCH only updates the fields specified in the request body.
5. DELETE
- Purpose: Used to delete a resource.
- Safe & Idempotent: Not safe, but it is idempotent.
- Example: Remove a user from the database.
Code Example (Node.js/Express)
app.delete('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User with ID ${userId} deleted`);
});
6. HEAD
- Purpose: Similar to GET but only returns headers, no body.
- Safe & Idempotent: Yes.
- Example: Check if a resource exists.
Code Example (Node.js/Express)
app.head('/users', (req, res) => {
res.status(200).end();
});
7. OPTIONS
- Purpose: Used to request the allowed HTTP methods for a resource.
- Safe & Idempotent: Yes.
- Example: Check available HTTP methods for
/users
endpoint.
Code Example (Node.js/Express)
app.options('/users', (req, res) => {
res.set('Allow', 'GET, POST, PUT, DELETE').end();
});
Note: OPTIONS is often used for CORS preflight requests.
Summary
Method | Action | Use Case |
GET | Retrieve data | Get list of users, fetch details |
POST | Create resource | Add new user, submit a form |
PUT | Replace resource | Update the whole user info |
PATCH | Update resource | Partially update user info |
DELETE | Remove resource | Delete a user or a product |
HEAD | Retrieve headers | Check if a resource exists |
OPTIONS | Check methods | CORS preflight request |
Conclusion
Understanding HTTP methods is essential for building well-structured and REST-compliant APIs. Each method serves a unique purpose, and knowing when to use GET, POST, PUT, PATCH, and DELETE can help you design better APIs.
In Node.js, these methods are implemented using the Express.js framework, which provides simple methods like app.get()
, app.post()
, and app.delete()
to handle these requests. By mastering these HTTP methods, you can create robust, clean, and RESTful web applications.
If you found this guide helpful, feel free to share it with others, and let us know in the comments if you’d like a deeper explanation of any of these methods.
Comments