1. Why Choose Node.js for Building APIs?¶
Node.js is a JavaScript runtime environment based on Chrome’s V8 engine. Its non-blocking I/O and single-threaded model make it particularly suitable for building high-concurrency network services. For RESTful APIs (a set of API design principles following REST architecture), Node.js paired with lightweight frameworks like Express enables quick implementation of simple and efficient backend services, making it ideal for beginners to get started.
2. Prerequisites: Install Node.js and Express¶
First, ensure your computer has Node.js installed (LTS version is recommended). Download it from the Node.js official website. After installation, open your terminal and verify with these commands:
node -v # Displays Node.js version
npm -v # Displays npm version
Next, create a project folder and initialize it:
mkdir node-api-demo
cd node-api-demo
npm init -y # Quickly generate package.json
Install the Express framework (we’ll use it to handle routes and responses):
npm install express
3. Express Basics: Create Your First Route¶
Express is a minimalist web framework focused on handling HTTP requests and responses. Create an app.js file and add the following code:
// Import Express module
const express = require('express');
// Create Express application instance
const app = express();
// Define port (customizable, e.g., 3000)
const PORT = 3000;
// Middleware: Parse JSON request bodies (required before route definitions)
app.use(express.json());
// Define a route to handle GET requests (fetch resources)
app.get('/', (req, res) => {
// req: Request object (contains parameters, headers, etc.)
// res: Response object (used to send data back to the client)
res.status(200).json({
message: 'Welcome to the Node.js RESTful API',
version: '1.0.0'
});
});
// Start the server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Code Explanation:
- app.get(): Handles GET requests. The first parameter is the route path ('/' for the root), and the second is a callback with req (request) and res (response) objects.
- res.status(200): Sets the HTTP status code to 200 (success). res.json() returns JSON data (more standard than res.send() for APIs).
- express.json(): Middleware to parse JSON request bodies (used for POST/PUT requests).
4. Handle Different HTTP Methods¶
RESTful APIs use different HTTP methods to express operations: GET (retrieve), POST (create), PUT (update), and DELETE (delete). Add these routes to app.js:
1. GET Request: Retrieve Resources¶
// Simulated user data (replace with a database in production)
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 }
];
// Get all users
app.get('/users', (req, res) => {
res.status(200).json({
success: true,
data: users
});
});
// Get a single user (using route parameters)
app.get('/users/:id', (req, res) => {
const userId = parseInt(req.params.id); // Convert parameter to number
const user = users.find(u => u.id === userId);
if (user) {
res.status(200).json({ success: true, data: user });
} else {
res.status(404).json({ success: false, message: 'User not found' });
}
});
Route Parameters: :id in /users/:id is a dynamic parameter, accessed via req.params.id (e.g., for fetching a specific user).
2. POST Request: Create Resources¶
// Create a new user (requires parsing request body)
app.post('/users', (req, res) => {
const newUser = {
id: users.length + 1, // Generate ID simply
name: req.body.name, // Extract name from request body
age: req.body.age
};
// Validate required fields
if (!newUser.name || !newUser.age) {
return res.status(400).json({
success: false,
message: 'name and age are required'
});
}
users.push(newUser);
res.status(201).json({ // 201 = "Created successfully"
success: true,
data: newUser
});
});
Note: The client must send JSON data (e.g., { "name": "Charlie", "age": 28 }) for POST requests, which is accessed via req.body.
3. PUT Request: Update Resources¶
// Update user information
app.put('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const index = users.findIndex(u => u.id === userId);
if (index === -1) {
return res.status(404).json({ success: false, message: 'User not found' });
}
// Merge request body with existing user data
users[index] = { ...users[index], ...req.body };
res.status(200).json({ success: true, data: users[index] });
});
4. DELETE Request: Delete Resources¶
// Delete a user
app.delete('/users/:id', (req, res) => {
const userId = parseInt(req.params.id);
const initialLength = users.length;
// Filter out the user with the specified ID
const newUsers = users.filter(u => u.id !== userId);
if (newUsers.length === initialLength) {
return res.status(404).json({ success: false, message: 'User not found' });
}
// Update the user list
users.length = 0;
users.push(...newUsers);
res.status(200).json({ success: true, message: 'User deleted' });
});
5. Handle 404 and General Responses¶
Express does not return 404 by default for unhandled routes. Add this middleware to handle 404 errors:
// 404 handler: Catches all undefined routes
app.use((req, res) => {
res.status(404).json({ success: false, message: `Route ${req.originalUrl} not found` });
});
6. Route Modularization (Advanced)¶
For larger projects, split routes into separate files for better organization.
1. Create routes/users.js:
const express = require('express');
const router = express.Router(); // Create a router instance
// Define user routes here (GET, POST, etc.)
router.get('/', (req, res) => { /* ... */ });
router.post('/', (req, res) => { /* ... */ });
module.exports = router;
2. Import into app.js:
const userRoutes = require('./routes/users');
app.use('/users', userRoutes); // Associate /users with the route file
7. Test Your API¶
Start the server:
node app.js
Test the API using tools like Postman or curl:
- GET /: Visit http://localhost:3000 to see the welcome message.
- GET /users: Retrieve the user list.
- POST /users: Send a JSON body ({ "name": "Charlie", "age": 28 }) to create a new user.
- GET /users/1: Fetch user with ID 1.
8. Summary¶
By following this guide, you’ve mastered the core skills for building RESTful APIs with Node.js:
1. Using Express to create services quickly.
2. Defining routes for different HTTP methods (GET/POST/PUT/DELETE).
3. Handling request parameters (route params, request body) and responses.
4. Managing error status codes (404, 400, etc.) and response content.
5. Implementing modular route design (advanced).
Next, connect to a database (e.g., MongoDB, MySQL) to replace mock data with real data and expand your API’s functionality!