Creating RESTful APIs with Node and Express.js

Posted by


In this tutorial, we will walk through the steps to build a REST API using Node.js and Express.js. REST, or Representational State Transfer, is a style of software architecture that defines a set of constraints for creating web services. Express.js is a popular web application framework for Node.js that simplifies the process of building APIs.

Prerequisites:
Before you begin, make sure you have Node.js installed on your machine. You can download it from the official Node.js website. You also need to have a basic understanding of JavaScript and HTTP.

Step 1: Set up a Node.js project
First, create a new directory for your project and navigate into it using the terminal. Run the following command to initialize a new Node.js project:

npm init

This command will guide you through the process of setting up your project. You can enter the default values for most of the prompts, but make sure to set the entry point to index.js.

Step 2: Install Express.js
Next, install Express.js as a dependency for your project. Run the following command in the terminal:

npm install express

This will add Express.js to your project’s node_modules directory and update your package.json file with the dependency.

Step 3: Create a basic Express server
Create a new file named index.js in your project directory. This file will serve as the entry point for your application. In index.js, write the following code to create a basic Express server:

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

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

This code sets up an Express server that listens for requests on port 3000 and returns ‘Hello World!’ when you visit the root URL http://localhost:3000 in a web browser.

Step 4: Create routes for the API
Now that you have a basic server set up, you can start defining routes for your API. Routes map HTTP methods (such as GET, POST, PUT, DELETE) to specific endpoints on your server. Add the following code to index.js after the existing route:

app.get('/api/users', (req, res) => {
  res.json([
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]);
});

app.get('/api/users/:id', (req, res) => {
  const { id } = req.params;
  res.json({ id, name: 'Alice' });
});

These routes define two endpoints: /api/users and /api/users/:id. The first endpoint returns a list of users, and the second endpoint returns a single user by ID.

Step 5: Handle POST requests
To handle POST requests and create new resources in your API, you can use the app.post method in Express. Add the following code to index.js:

app.use(express.json());

app.post('/api/users', (req, res) => {
  const { name } = req.body;
  const newUser = { id: 3, name };
  res.status(201).json(newUser);
});

This code adds support for parsing JSON request bodies with express.json() and creates a route for creating new users in the API.

Step 6: Handle PUT and DELETE requests
To update existing resources in your API, you can use the app.put method in Express. Similarly, you can use the app.delete method to delete resources. Add the following code to index.js:

app.put('/api/users/:id', (req, res) => {
  const { id } = req.params;
  const { name } = req.body;
  res.json({ id, name });
});

app.delete('/api/users/:id', (req, res) => {
  const { id } = req.params;
  res.json({ message: `User ${id} deleted` });
});

These routes handle PUT and DELETE requests for updating and deleting users in the API, respectively.

Step 7: Test the API
To test your API, start the server by running the following command in the terminal:

node index.js

Visit http://localhost:3000/api/users in a web browser to see the list of users. You can also test the other CRUD operations (POST, PUT, DELETE) using tools like Postman or cURL.

Conclusion:
In this tutorial, you learned how to build a REST API using Node.js and Express.js. You created routes for handling HTTP requests, implemented CRUD operations for manipulating resources, and tested the API using Postman. REST APIs are a powerful tool for building web services that can be consumed by client applications. Experiment with different endpoints, middleware, and error handling to further customize your API and make it production-ready. Happy coding!

0 0 votes
Article Rating
23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@jdgjbb
2 months ago

what to do anyone help , erorr showing res not defined

@ExploreSciFi
2 months ago

a very underrated playlist and YouTuber… 😢

@ishitatomar023
2 months ago

Hey can someone explain me pls mere isme package.json file nhi ban rhi

@shaadakhtar5986
2 months ago

Every time I create a new package.json and write start in script, 'npm start' starts the server mentioned in the latest package. What about others?

@santoshbhujbal5650
2 months ago

Thank you sir❤❤❤❤

@ArunKumar_237
2 months ago

Thank you

@user-tk2rb5xp1i
2 months ago

good

@mohsinalijafery2217
2 months ago

Wow… Thanks so much for these incredible tutorials…

@DesertCentipede
2 months ago

good explanation skills with soothing voice

@User-yb3yc
2 months ago

Ek baar mai smj gaya bro . Great Teacher with perfect explanation

@deepakthevlog444
2 months ago

Thanks sir. I saw you with Hitesh sir first time from there i continue following you.

@user-be4kh9cg3k
2 months ago

thank you so much for all the Videos great Job .. can you please also make videos on step functions

@modanwalpriti8769
2 months ago

It's really very best playlist for NODEJS

@chintukumar5726
2 months ago

in mac 8000 not opening new web window and not server start what should i do

@2ameridiem
2 months ago

amazing video piyush! just have a quick question. do we not need to export the mock data? you didn't export it but still the require function worked and i'm wondering if exporting is optional? will it work if i explicitly do it as-

const mock_data=[ ];
module.exports=mock_data;

@tehniatmirza1439
2 months ago

great explanation

@souravkumar961
2 months ago

Thank you so much for this wonderful video

@_official_cartoon_lofi
2 months ago

Mom Says No Girlfriend 🤣

@imranyasin169
2 months ago

My learning
User find method when fetching single user data instead of using filter method because filter return the array and find return the object

@sanjaytk
2 months ago

Excellent clarification, thank for his awesome video