Open In App

Creating a simple JSON based API using Node.js

Improve
Improve
Like Article
Like
Save
Share
Report

API (Application Programming Interface) results are commonly used by applications, sometimes to withdraw information from their huge databases, check the status of a particular data, or sometimes they depend on third-party APIs to display additional information related to users.
Here we will make a simple public JSON based Chemistry API, which can be used in any programming language to display the results.

Steps to create API:

  • Step 1: Install Node.js from based on your Operating System, and system requirements.
  • Step 2: Initialize a blank folder, in which you would build the API. In that folder, create a blank JS file, called index.js
  • Step 3: Open command prompt and go to the created directory by using CD (path of the folder).
  • Step 4: Type npm init and go through the steps, answering the asked questions.

For building the Chemistry API, we would need to create an empty JSON file, and paste the JSON data. Now we have to include a few NodeJS libraries and set up the port for the API.




var fs = require('fs');
  
// json file with the data
var data = fs.readFileSync('chemistry.json');
  
var elements = JSON.parse(data);
const express = require("express");
const app = express();
  
// To solve the cors issue
const cors=require('cors');
   
app.listen(process.env.PORT, 
    () => console.log("Server Start at the Port"));
   
app.use(express.static('public'));
app.use(cors());


Designing the endpoints of the API:




// when get request is made, alldata() is called
app.get('/elements', alldata);
  
function alldata(request, response) {
      
    // Returns all information about the elements
    response.send(elements);
}


Here, “/elements” is the endpoint, and when a get request is made to the API, at /elements endpoint, alldata() function is called. Now alldata() function has two parameters (request and response). Using response.send(), the response is returned to the user.




app.get('/elements/:element/', searchElement);
  
function searchElement(request, response) {
    var word = request.params.element;
    word = word.charAt(0).toUpperCase()
        + word.slice(1).toLowerCase();
       
    if(elements[word]) {
        var reply = elements[word];         
    }
    else {
        var reply = {
            status:"Not Found"
        }
    }
       
    response.send(reply);
}


“/:element/” is the variable endpoint, for requests regarding any specific element.

Combined all three sections of code to create index.js file.

Filename: index.js




var fs = require('fs');
   
// json file with the data
var data = fs.readFileSync('chemistry.json');
   
var elements = JSON.parse(data);
const express = require("express");
const app = express();
   
// To solve the cors issue
const cors=require('cors');
    
app.listen(process.env.PORT, 
    () => console.log("Server Start at the Port"));
    
app.use(express.static('public'));
app.use(cors());
  
// when get request is made, alldata() is called
app.get('/elements', alldata);
   
function alldata(request, response) {
       
    // Returns all information about the elements
    response.send(elements);
}
  
app.get('/elements/:element/', searchElement);
  
function searchElement(request, response) {
    var word = request.params.element;
    word = word.charAt(0).toUpperCase()
        + word.slice(1).toLowerCase();
       
    if(elements[word]) {
        var reply = elements[word];         
    }
    else {
        var reply = {
            status:"Not Found"
        }
    }
       
    response.send(reply);
}


Now, you all can create a simple JSON based API, and upload the whole code in GitHub, and host it on Heroku. We have included the Github repository link and API docs, feel free to explore the projec.



Last Updated : 07 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads