Build an API with NodeJS

Nishant Mishra
2 min readJul 30, 2022

--

In this guide, you will build a Node.js REST API with the Express Framework, and make test requests to it on Postman.

Prerequisites

Before you begin this guide you’ll need the following:

Step 1 — Build and Run an Express Server with Node.js

In this step, you will write up an Express server with Node.js and run it locally.

First, Setup Express.

npm install express

the make a new node project

npm init

After the setup you should have one directory node_modules and two files package.json & package-lock.json.

Next, you will write a simple “Hello World” app. Create an index.js file and add the code below to it.

const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.end('Hello World!');
});
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`)
});

Finally, you should run the server with a command that tells Node.js to run your Express sever:

node index.js

Opening http://localhost:3000/ should return a “Hello World” message as expected.

Stop the server by running CTRL + C.

In the next step, you will add an API endpoint to your server.

Step 2 — Create a GET Endpoint

In this step, you are going to create an endpoint that returns a list of all the movies stored in a JSON file.

Let’s consider that you have a JSON database of movies in a file named movies.json that lies in the same directory as your index.js file.

[
{
"id": 1,
"title": "Star girl"
},
{
"id": 2,
"title": "Five feet apart"
},
{
"id": 3,
"title": "Fifty shades of Grey"
},
{
"id": 4,
"title": "Titanic"
}
]

First, you would need to read the file contents and then return the data obtained to the client that made the GET request to your server.

We will make use of the fs module to read the file. How to do this is shown below.

const express = require('express')
const app = express()
const port = 3000
const fs = require('fs')
app.get('/', (req, res) => {
res.end('Hello World!');
});
app.get("/list_movies", (req, res) => {
fs.readFile(__dirname + '/' + 'movies.json', (err, data) => {
res.end(data);
});
});
app.listen(port, () => {
console.log(`app listening at http://localhost:${port}`)
});

Next, start up the server by running node index.js.

Finally, opening http://localhost:3000/list_movies should return the same data found in the movies.json file, as expected.

Stop the server by pressing CTRL + C.

Congratulations!!! You have managed to build and locally serve a Node.js REST API built with Express!

And there you have it. You managed to build a Node.js API server with Express.

Congratulations!!!

--

--