About Lesson
HTTP Methods in REST API (Including PATCH)
HTTP Method | Purpose | Example URL | Example Action |
GET | Retrieve data | /users | Get a list of users |
POST | Create new data | /users | Add a new user |
PUT | Update entire data | /users/1 | Replace user with ID 1 |
PATCH | Update partial data | /users/1 | Modify only specific fields of user with ID 1 |
DELETE | Remove data | /users/1 | Delete user with ID 1 |
Example
JavaScript
const express = require('express');
const app = express();
const port = 3000;
app.use(express.json());
let users = [
{ id: 1, name: "John Doe", email: "john@example.com" },
{ id: 2, name: "Jane Doe", email: "jane@example.com" }
];
app.get('/', (req, res) => res.send('Welcome to our REST API!'));
app.get('/users', (req, res) => res.json(users));
app.get('/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
});
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name,
email: req.body.email
};
users.push(newUser);
res.status(201).json(newUser);
});
app.put('/users/:id', (req, res) => {
let user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: "User not found" });
user.name = req.body.name;
user.email = req.body.email;
res.json(user);
});
app.patch('/users/:id', (req, res) => {
let user = users.find(u => u.id === parseInt(req.params.id));
if (!user) return res.status(404).json({ message: "User not found" });
if (req.body.name) user.name = req.body.name;
if (req.body.email) user.email = req.body.email;
res.json(user);
});
app.delete('/users/:id', (req, res) => {
users = users.filter(u => u.id !== parseInt(req.params.id));
res.json({ message: "User deleted" });
});
app.listen(port, () => console.log(`Server running at http://localhost:${port}`));
REST API Best Practices
- Use Proper HTTP Methods – Follow the correct method for each action
- Use Meaningful Endpoints – Instead of /getUserData, use /users.
- Use JSON Format – JSON is lightweight and widely used.
- Implement Authentication – Use JWT (JSON Web Token) or API keys for security.
- Use Status Codes Correctly – Always return the right status codes.