1/1/1970
Resources
In this guide, we'll cover the essentials of setting up a RESTful API using Express in Node.js. We will focus on best practices and understand how to handle JSON data.
Structure Your API :
A RESTful API typically includes the following endpoints:
GET /api/users - List all users.GET /api/users/:id - Get a user by ID.POST /api/users - Create a new user.PUT /api/users/:id - Replace a user by ID (Create if doesn’t exist).PATCH /api/users/:id - Update a user by ID.DELETE /api/users/:id - Delete a user by ID.C - Create - POST
R - Read - GET
U - Update - PUT, PATCH
D - Delete - DELETE
Create Mock Data : If you don’t have a database yet, use mock data:
.json) file in your project directory.Project Setup:
# Initialize the Project
npm init# Install Express
npm install express# Create a empty `index.js`
echo. > index.jsSet Up Express:
// Set Up Express in `index.js`
const express = require('express');
const users = require('./data/users.json'); // Path to your JSON file
const app = express();
const port = 8000;
// Implementation here....
app.listen(port, () => console.log(`Server running at http://localhost:${port}`);
);Define API Endpoints:
READ:
// REST APIs - JSON
// List All Users
app.get('/api/users', (req, res) => {
return res.json(users);
});POST)by GPT ( because skipped by him for future video) :
Note:
GET Request, so POST, PATCH & DELETE Requests are problematic.postman for such requests.// Create a new user
app.post('/api/users', (req, res) => {
const newUser = req.body; // Ensure you use body-parser middleware
users.push(newUser);
res.status(201).json(newUser);
});GET)Note:
Render Data in HTML Document:
// List All Users Names Render in HTML
app.get('/users', (req, res) => {
const html = `
<ul>
${users.map((user) => `<li>${user.first_name}</li>`).join('')}
</ul>
`;
res.send(html);
});
// Example -> // http://localhost:8000/usersReturn Data as API (JSON) :
// Get all users
app.get('/api/users', (req, res) => {
return res.json(users); // return optional in oneline
});
// Example -> http://localhost:8000/api/users//Get user by ID
app.get('/api/users/:id', (req, res) => {
// Convert string `id` to no. because we comare using `===`
const id = Number(req.params.id)
const user = users.find((user) => user.id === id);
return res.json(user);
});
// Example -> http://localhost:8000/api/users/2:id -> its mean it is a variable / Dynamic Value
POST/PUT)by GPT ( because skipped by him for future video) :
// Partial Update User by ID
app.patch('/users/:id', (req, res) => {
let user = users.find(u => u.id === parseInt(req.params.id));
if (user) {
// Merge only provided fields in req.body into the user object
Object.assign(user, req.body);
res.json(user); // Return the updated user
} else {
res.status(404).send('User not found');
}
});
// Example -> http://localhost:8000/api/users/3// Full Update User by ID
app.put('/users/:id', (req, res) => {
let user = users.find(u => u.id === parseInt(req.params.id));
if (user) {
// Replace the entire user object with the new data from req.body
user = { id: user.id, ...req.body }; // Ensures user ID remains unchanged
res.json(user); // Return the updated user
} else {
res.status(404).send('User not found');
}
});
// Example -> http://localhost:8000/api/users/1by GPT ( because skipped by him for future video) :
// Delete User by ID
app.delete('/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === parseInt(req.params.id));
if (index !== -1) {
users.splice(index, 1);
res.status(204).send();
} else {
res.status(404).send('User not found');
}
});api/users/ is used by GET and POST Request and Similarly /api/users/:id by PUT GET & DELETE.
// `/api/user/` Route
app
.route('/api/users/')
.get((req,res)=>{...})
.post((req,res)=>{...})
// `/api/user/:id` Route
app
.route('/api/users/:id')
.get((req,res)=>{...})
.patch((req,res)=>{...})
.delete((req,res)=>{...})Introduction to RESTful APIs
Core Principles of REST:
HTTP Methods and Their Usage
GET /users retrieves all users. GET /users/1 retrieves the user with ID 1.POST /users with a request body containing user details creates a new user.PUT /users/1 with a request body containing updated user details updates the user with ID 1.PATCH /users/1 with a request body containing partial user updates updates only the specified fields of the user with ID 1.DELETE /users/1 deletes the user with ID 1.Design Considerations for RESTful APIs :
200 OK, 404 Not Found, 500 Internal Server Error)./v1/users, /v2/users).Best Practices: