Build an API using NodeJS

Build an API using NodeJS

In this blog, I'll guide you on how I made my first API using NodeJS

Some pre-requisites before starting:

What is NodeJS?

Node.js is a free open-source server environment which runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) and uses JavaScript on the server.

Node.js uses asynchronous programming!

What I mean by that is: NodeJS enables your program to start a potentially long-running task and still be able to be responsive to other events while that task runs, rather than having to wait until that task has finished.

Hence, Node.js eliminates the waiting and simply continues with the next request.

Setting Up the Project:

  1. Step-1: To install NodeJS first (according to your operating systems)

  2. Step-2: To install and set up ExpressJS next. It will help us to make a server in NodeJS.

    • Make a new folder, and inside that folder open your terminal.

    • I've made a folder named new API

    • Now, install express using the following command in your terminal:

      npm install express

  3. Step-3: Make a new Node project, by using the following command.

    • npm init

      the package name will be -> new API

      author -> <your name>

      package.json will also get installed using the npm init command.

  4. Step-5: To open our code editor. I'm using VS Code and the command to open VS code using the terminal is:

    code .

After the setup, we can see that we have one directory node_modules and two files package.json & package-lock.json.

Starting with the Project:

After following the steps up till here, make a new file called index.js

Inside that file, we will write the following JavaScript code to make a simple "Hello World" App using express and node to see how things work.

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

Explanation:

const express = require('express')

const app = express()

  • 1st line says that we have required express and in the 2nd line we are calling that function in our app.

const port = 4000

  • We have set our Port to 4000, where we will be watching all changes locally.

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

  • We will create a get endpoint, app.get

    '/' is the home directory

  • Since we want to write "Hellow World" we need to make a REQUEST for that RESPONSE

  • req is for request and res is for the response.

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

RUN your server:

Run the server with a command that tells Node.js to run your Express server in your terminal:

node index.js

We get the following Output:

After some changes, if we wish to see the modified outputs again we need to run the following command:

^C

node index.js

Creating an Endpoint:

We are going to create an endpoint that returns a list of all the movies stored in a JSON file.

Let’s make a JSON database of movies in a file named movies.json that lies in the same directory as our index.js file.

I'm making a anime.json data file in my code editor. (Since I'm a huge weeb haha 👀)

[
    {
      "id": 1,
      "title": "Your Name"
    },
    {
      "id": 2,
      "title": "Bakuman"
    },
    {
      "id": 3,
      "title": "One Piece"
    },
    {
      "id": 4,
      "title": "Naruto"
    }
]

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.

FS or FLS is File System Module that helps us to read the data inside a file. For example, our JSON data in a .json file.

  • At first, we will require the fs module

    We can do that by adding the following piece of code to our index.js file:

      const fs = require('fs')
    

Now add this code to your index.js file:

app.get("/list_anime", (req, res) => {
    fs.readFile(__dirname + '/' + 'anime.json', (err, data) => {
        res.end(data);
    });
});

EXPLANATION:

This code says I've made a directory of the list of anime names.

We called the function using req (request) & res (response).

Then we added fs.readFile function. which is ultimately reading the .json file.

Final Code:

const express = require('express')
const app = express()
const port = 4000;
const fs = require('fs');

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

app.get("/list_anime", (req, res) => {
    fs.readFile(__dirname + '/' + 'anime.json', (err, data) => {
        res.end(data);
    });
});


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

add this to index.js file and again start up the server by running node index.js.

Finally, opening http://localhost:4000/list_anime should return the same data found in the anime.json file, as expected.

Stop the server by pressing CTRL + C.

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

Congratulations!!! 🥳🥳🥳