Skip to main content

Archive

Show more

Node.js Building RESTful APIs with Express.js

Node.js Building RESTful APIs with Express.js

Express.js is a popular web application framework for Node.js that simplifies the process of building web servers and RESTful APIs. With Express.js, you can easily define routes, handle HTTP requests and responses, and implement middleware for additional functionality.


1. Installing Express.js

You can install Express.js in your Node.js project using npm:

npm install express

2. Creating a Basic API Server

To create a basic API server with Express.js, define routes for different HTTP methods and handle requests using route handlers.

Example:

const express = require('express');
const app = express();
const PORT = 3000;

// Define a route for GET request
app.get('/api/users', (req, res) => {
    res.json({ users: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }] });
});

// Define a route for POST request
app.post('/api/users', (req, res) => {
    // Logic to create a new user
    res.status(201).send('User created successfully');
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

In this example, we define routes for GET and POST requests to manage users. The res.json() method is used to send a JSON response for GET requests, and the res.status() and res.send() methods are used for POST requests.


3. Handling Route Parameters

You can handle route parameters in Express.js to create dynamic routes that respond to different values.

Example:

// Define a route with route parameter
app.get('/api/users/:id', (req, res) => {
    const userId = req.params.id;
    // Logic to retrieve user by ID
    res.json({ id: userId, name: 'John' });
});

This example defines a route for GET requests to retrieve user details by ID. The :id in the route path acts as a placeholder for the user ID.


4. Conclusion

Express.js simplifies the process of building RESTful APIs in Node.js by providing a clean and expressive framework for defining routes, handling requests and responses, and implementing middleware. Whether you're building a simple API or a complex web application, Express.js offers the flexibility and power you need to get the job done efficiently.

Comments