Today’s Offer Enroll today and get access to premium content.
App Store Google Play

Building a Simple REST API with Node.js and Express

This tutorial provides a step-by-step guide to creating a simple RESTful API using Node.js and the Express framework. Learn how to set up your environment, create routes, and handle requests.

6 lessons
Setting Up Your Environment
Before diving into code, we need to set up our development environment.
Concept walkthrough

Setting Up Your Environment

In this section, we will install Node.js and Express to start our project.

  • Download and install Node.js from Node.js official website.
  • Verify installation by running node -v and npm -v in your terminal.
Expected output
Node.js and npm should be installed successfully.
Lesson 1 of 6
Creating Your Project
Now that we have our environment set up, let's create a new Node.js project.
Concept walkthrough

Creating Your Project

Use the following commands to create a new project directory and initialize it.

mkdir my-api
cd my-api
npm init -y
Expected output
A new Node.js project is created with a package.json file.
Lesson 2 of 6
Installing Express
Next, we will install the Express framework, which will help us build our REST API.
Concept walkthrough

Installing Express

Run the following command to install Express in your project.

npm install express
Expected output
Express is installed and added to your package.json file.
Lesson 3 of 6
Creating the Server
Let’s create a basic server using Express that listens for requests.
Concept walkthrough

Creating the Server

Create a file called server.js and add the following code to set up your 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 is running on http://localhost:${PORT}`);
});
Expected output
The server should start and listen on port 3000, displaying 'Server is running on http://localhost:3000'.
Lesson 4 of 6
Creating API Endpoints
Now, let’s create some API endpoints that handle different HTTP methods.
Concept walkthrough

Creating API Endpoints

Modify your server.js to include the following endpoints:

app.get('/api/data', (req, res) => {
    res.json({ message: 'GET request received' });
});

app.post('/api/data', (req, res) => {
    res.json({ message: 'POST request received' });
});
Expected output
You can make GET and POST requests to '/api/data' and receive JSON responses.
Lesson 5 of 6
Testing Your API
Finally, we will test our API endpoints using tools like Postman or curl.
Concept walkthrough

Testing Your API

Use Postman or curl to test your API:

curl -X GET http://localhost:3000/api/data
curl -X POST http://localhost:3000/api/data
Expected output
You should receive JSON responses for both GET and POST requests.
Lesson 6 of 6