Building a basic API in Node

  • Post category:Node
  • Reading time:2 mins read

In this post, we will learn how to build a simple API in node.js.

Building a basic API in Node

I am using the JSON code below for creating a simple API in the node. I can name this JSON file as data.json. Now, I will be using this data.json file in my node.js code.

[
  {
    "id": "1",
    "name": "youtube",
    "Description": "Video streaming"
  },
  {
    "id": "2",
    "name": "facebook",
    "Description": "Social media"
  },
  {
    "id": "1",
    "name": "Amazon",
    "Description": "Online shopping"
  }
]
const http = require("http");
const url = require("url");
const fs = require("fs");

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

const server = http.createServer((request, response) => {
  const pathName = request.url;
  if (pathName === "/") {
    response.writeHead(200, { "content-type": "application/json" });
    response.end(getData);
  }
});

server.listen(8000, "localhost", () => {
  console.log("Server has started on port 8000");
});

API Response output

simple api example in node.js

I choose to write the code stored in the getData variable outside of the server because whenever there is a new request, the server code gets executed each time.

So, by writing code this way, we do not need to read the data each time whenever there is a new request. We are reading the data once, and whenever the “/” URL gets hit, we simply send the data without reading the data file each time.

Note:

__dirname is used to get the correct directory location of the file. So, whenever you are accessing a file in your node code, use __dirname.

I used “content-type”: “application/json” as the content which I am getting from the data.json file is a JSON format content.

Share this