Introduction
APIs play a crucial role in modern development, facilitating communication between different software systems. Let's dive into the essentials of creating a basic REST API using Node.js and Express.
Step 1: Install Node.js
Ensure you have Node.js installed on your machine. If not, visit Node.js and follow the simple installation process. 🛠️
Step 2: Initialize the Project
Create an empty directory for your project, navigate into it, and initialize the project using npm init
. Next, create an empty JavaScript file (e.g., index.js) and install Express, a minimal and easy-to-learn Node.js framework, using the command npm install express
. 📦
mkdir rest-api
cd rest-api
npm init
npm install express
Content of the index.js
file
const express = require('express');
const app = express();
const port = 3000;
Step 3: Starting the Server
Initialize your Express app and start the local server on port 3000. The listen()
function establishes the connection, taking the port number and an optional callback function. Accessing "localhost:3000" in the browser will yield a "404 Not Found" response, as we haven't defined any endpoints yet.
Content of the index.js
file
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
node index.js
Output
Server is running at http://localhost:3000
Install a tool like Hoppscotch for testing and building APIs. 🚦
Step 4: Create Endpoints
Utilize the get
method to create HTTP GET requests. Define endpoints by specifying the route and a callback function handling the request and response. For instance, creating a "/users" endpoint to display user data involves using the send method to return data to the client.
To demonstrate a POST request endpoint, add middleware to parse the JSON body. Implement logic for the "/user/3" route, ensuring a "400 Bad Request" status code is thrown if the required data is missing.
Content of the index.js
file
app.get('/users', (req, res) => {
// Example data for demonstration
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.send(users);
});
// POST endpoint with middleware for JSON parsing
app.use(express.json()); // Middleware for parsing JSON
app.post('/user/3', (req, res) => {
const { name } = req.body;
// Check if 'name' is provided in the request body
if (!name) {
return res.status(400).send('Bad Request: Missing name in the request body.');
}
// Logic to handle the POST request
res.send(`User ${name} added successfully.`);
});
Combining all the steps, your complete index.js
file would look like this 👇
const express = require('express');
const app = express();
const port = 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
// Endpoint for GET request at '/users'
app.get('/users', (req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.send(users);
});
// Middleware to parse JSON body
app.use(express.json());
// Endpoint for POST request at '/user/3'
app.post('/user/3', (req, res) => {
const { name } = req.body;
if (!name) {
return res.status(400).send('Bad Request: Missing name in the request body.');
}
res.send(`User ${name} added successfully.`);
});
Let's try to access this endpoint now.
Restart the server, and you've successfully built a basic REST API. You can extend this by creating additional endpoints using the same technique.
Conclusion
Building a REST API with Node.js and Express is straightforward. Happy coding! ✨👩💻🚀
Top comments (0)