Creating a Very Simple Web API in Node.JS


Reading time: 30 minutes

In this article, we will explore how to build a simple API in Node.JS. We will cover the basics of an API before going into the implementation details.

⭐ What is an API ?


Localhost-_-API

API stands for Application Programming Interface. It is a piece of software that can be used by another piece of software, to allow applications to talk to each other.

Web API in particular simply refers to an app that sends data to a client whenever a request comes in. Here, we have client and server talking to each other through the API. This is the most widely used kind of API out there. However, APIs aren't always used to send data and aren't always related to web development or JavaScript.

So, the Application in API can refer to many things, as long as the piece of software can relatively stand-alone. For instance,

  • Node.js fs's API or HTTP API
  • Browser's DOM Javascript API
  • In OOP, when we expose methods to the public, we're creating an API.

Anyways, a Web API is the most crucial for us to understand in the context of Node. So, let's get started and learn how to build a very simple web API, using JSON data from a file.

⭐ Step 1: Creating a Web Server


For creating a web server, you may refer to the following article .

⭐ Step 2: Implementing routing


You may refer to the following article to implement routing .

⭐ Step 3: Creating the API


📝 3a. Understanding the file structure:


To get started, download the starter files for this part from here.
Let us understand the file structure in the starter folder -

starter
|-- dev-data
      |-- apiData.json     
|-- index.js
  1. index.js contains our code for creating a web server and implementing some basic routes. We will be adding our code for the API in the api route specified in index.js.
  2. The folder dev-data contains all the data files needed for development.
  3. apiData.json is present inside dev-data folder and contains some dummy JSON data.

📖 JSON


JSON stands for JavaScript Object Notation. It is a format mainly used for interchange of data between two applications. It is human-readable and is also easy for machines to parse and generate.

Basic JSON Syntax :


JSON is based on the JavaScript object notation.Its syntax is derived from JavaScript object notation syntax:

  • Data is in key/value pairs (key->value)
  • Data is separated by commas
  • Curly braces hold {objects}
  • Square brackets hold [arrays]

Key-value pair :


Syntax :

"field-name" :  value

The field-name is always a string wrapped in double-quotes.

For instance,

"name" : "Priyanka"

JSON Objects :


Syntax :

{"field-1" :  value, "field-2":value}

It is similar to a JavaScript object. The keys are always string, while the value can be of any data type (string, number, array or even another object).

For instance,

    { 
    "name":"Priyanka",
    "_id":14
    }

Note: The key-value pairs inside the object are seperated with commas.

JSON Arrays :


Syntax :

[data-1,data-2,data-3]

In JSON, array values/data must be of type string, number, object, array, boolean or null.

For instance,

var obj = ["Priyanka", 14, true] 

The elements of an array can be accessed using index number, For eg.

console.log(obj[1])

will give

14

as output

📝 3b. Writing Code for the API Route :


Now, we are all ready to write our code for the API, so include the following code in the api route.

    1. else if (pathname === "/api") {
    2. fs.readFile(`./dev-data/apiData.json`, "utf-8",(err,data)=>{
    3. res.writeHead(200, {
    4. "Content-type": "application/json"});
    5. res.end(data);
    };}

Now, let's understand what's happening -

In line 1 : We are handling the route request for /api.
In line 2 : We are fetching the contents of the file using the fs(file-system) module. Do not forget to include it using const fs = require('fs');.

Here, we have fetched the contents from our apiData.json file, which includes our dummy JSON data.
In line 3 : we have specified the status code that is 200 (OK).
In line 4 : we have specified the Content-type as application/json, since we are fetching JSON from the file.
In line 5 : We have sent the data received as a parameter in the callback function as the response.

Now, save the file, traverse to the working directory in the terminal, and run node index.js to start your server. Traverse to 127.0.0.1:8000/api to see the results of your api request.

node-i

Now, the code works absolutely fine, but it is not efficient. We can make few modifications to make it more better.

1. Using the variable __dirname :


In our code, we have specified the route as - `./dev-data/apiData.json`. Now, this is not the only way of locating files.

In Node, this . represents refers to the directory from which we run the node command in our terminal. Here . refers to our directory which contains our index.js file and dev-data folder.

But we could have run our command somehwhere else, and then this . would have referred something else.

For instance, here . refers to the final directory.

terminal-1

And here, . refers to the desktop,

terminal-2

So, using . to locate files in our program is not always ideal. And we have a better way - So, all Node.js scripts get access to a variable named __dirname, and this variable always translates to the directory in which the script that we're currently executing is located.

So, it is a good practice to use the __dirname variable. So replace `./dev-data/apiData.json` with `${__dirname}/dev-data/apiData.json`.

2. Using fs.readFileSync to fetch the data beforehand :


Our program is not yet efficient since each time someone accessed the route, the file is read and then the data is rendered.

Instead, we can read the file beforehand, and when the route is accessed, we can simply send back the data, without having to read it each time the user requested.

So include the following code before the server is created, that is before this line - const server = http.createServer((req, res) => {.

const data = fs.readFileSync(`${__dirname}/dev-data/apiData.json`, "utf-8");

And modify the api route as -

else if (pathname === "/api") {
    res.writeHead(404, {
      "Content-type": "application/json"
    });
    res.end(data);
  }

Now, save your file, use Ctrl+C or Cmd+C to exit the current server, Use node index.js to run the server. Go to 127.0.0.1:8000/api in your browser, and we get the following response.

node-i-1

It works the same, but this time it is much better and efficient.

So, that was our very simple API that allows the user to simply request the data from the application with one single API call.

And We're all done finally for creating this Web API! 🎉

In case you missed something, you can refer the code here.

References/ Further Reading :


  1. https://nodejs.org/dist/latest-v6.x/docs/api/
  2. https://nodejs.org/api/http.html