Skip to content
- Courses
- DSA to Development
- Newly Launched!
- For Working Professionals
- For Students
- GATE Exam Courses
- All Courses
- Tutorials
- Data Structures & Algorithms
- DSA for Beginners
- Data Structures
- Algorithms
- Complete DSA Tutorial
- Competitive Programming
- Company Wise SDE Sheets
- DSA Cheat Sheets
- Top 100 DSA Interview Questions Topic-wise
- 100 Days of Code
- Python
- ML & Data Science
- Machine Learning
- Data Science Tutorial
- Data Science Packages
- Data Visualization
- Data Analysis
- Deep Learning
- NLP Tutorial
- OpenCV Tutorial
- Interview Questions
- System Design
- Interview Corner
- Languages
- Web Development
- HTML
- CSS
- JavaScript
- TypeScript
- ReactJS
- Node.js
- PHP
- AngularJS
- jQuery
- Web Development Using Python
- Web Design
- 100 Days of Web Development
- CS Subjects
- DevOps And Linux
- School Learning
- GATE
- GeeksforGeeks Videos
- Data Structures & Algorithms
- Jobs
- Practice
- All DSA Problems
- Problem of the Day
- Company Wise Coding Practice
- GfG SDE Sheet
- Practice Problems Difficulty Wise
- Language Wise Coding Practice
- Curated DSA Lists
- Contests
-
- Full Stack Course
- NodeJS Tutorial
- NodeJS Exercises
- NodeJS Assert
- NodeJS Buffer
- NodeJS Console
- NodeJS Crypto
- NodeJS DNS
- NodeJS File System
- NodeJS Globals
- NodeJS HTTP
- NodeJS HTTP2
- NodeJS OS
- NodeJS Path
- NodeJS Process
- NodeJS Query String
- NodeJS Stream
- NodeJS String Decoder
- NodeJS Timers
- NodeJS URL
- NodeJS Interview Questions
- NodeJS Questions
- Web Technology
Last Updated : 07 Mar, 2024
Summarize
Comments
Improve
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) {
See AlsoThe power of JSON: what's behind the popularity?ReactJS: Understanding package.json and Package-lock.json.JSON is incredibly slow: Here’s What’s Faster!Specifying dependencies and devDependencies in a package.json file | npm Docs// 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.
Please Login to comment...
Similar Reads
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
Using Restify to Create a Simple API in Node.js
Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RESTful services. It’s lightweight, fast, and specif
6 min read
Creating a REST API Backend using Node.js, Express and Postgres
JavaScript Backend can be developed using Node.js, Express, and Postgres. This backend can do Query operations on the PostgreSQL database and provide the status or data on the REST API. Installation Requirement: Node.js: Install the Node.js on WindowsInstall the Node.js on LinuxPostgreSQL: Install Postgres on WindowsInstall Postgres on LinuxInstall
3 min read
Node.js Building simple REST API in express
Let's have a brief introduction about the Express framework before starting the code section:Express: It is an open-source NodeJs web application framework designed to develop websites, web applications, and APIs in a pretty easier way. Express helps us to handle different HTTP requests at specific routes.As it is NodeJs web framework so make sure
2 min read
Creating a Simple Image Editor using JavaScript
In this article, we will be creating a Simple Image Editor that can be used to adjust the image values like brightness, contrast, hue, saturation, grayscale, and sepia. Image editors allow one to quickly edit pictures after they have been captured for enhancing them or completely changing their look. Using a combination of various values, one can g
10 min read
How to parse JSON object using JSON.stringify() in JavaScript ?
In this article, we will see how to parse a JSON object using the JSON.stringify function. The JSON.stringify() function is used for parsing JSON objects or converting them to strings, in both JavaScript and jQuery. We only need to pass the object as an argument to JSON.stringify() function. Syntax: JSON.stringify(object, replacer, space); Paramete
2 min read
How to transforms JSON object to pretty-printed JSON using Angular Pipe ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will see How to use pipe to transform a JSON object to pretty-printed JSON using Angular Pipe. It meaning that it will take a JSON object string and return it pretty-p
3 min read
Flask - (Creating first simple application)
Building a webpage using python.There are many modules or frameworks which allow building your webpage using python like a bottle, Django, Flask, etc. But the real popular ones are Flask and Django. Django is easy to use as compared to Flask but Flask provides you with the versatility to program with.To understand what Flask is you have to understa
6 min read
Simple POST request using the fetch API
The fetch() method, like the XMLHttpRequest and Axios request, is used to send the requests to the server. The main difference is that the Fetch API uses Promises, which enables a simpler and cleaner API. You will get the whole Get and Post method using fetch API Syntax: fetch(url, { config }) .then(res => { // Handle response }) .catch(err =
2 min read
How to use simple API using AJAX ?
AJAX (Asynchronous JavaScript and XML) is a set of tools used to make calls to the server to fetch some data. In this article, we will see how to implement a simple API call using AJAX. Prerequisites: Basic knowledge of AJAX and its function. You can learn all the basics from here. What are basic building? We will be fetching employee's names from
3 min read
How to make simple PUT request using fetch API by making custom HTTP library ?
The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. It will be taking a fake API that will contain Array as an example and from that API we will show to PUT/Update data by fetch API method by making custom HTTP library. The API used in this tutorial is: https:
2 min read
Simple DELETE request using fetch API by making custom HTTP library
Why fetch() API method is used? The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object. We will be taking a fake API which will contain Array as an example and from that API we will show to DELETE data by fetch API method by making custom HTTP library. The API use
2 min read
Simple Text Editor using File System Access API
In this article, we will create a simple text editor like application that we can use to open, edit, and save text files with the help of File System Access API. File System Access API enables us to interact with files on our local devices like photo and video editors. When the user gives permission, this helps us to read or save changes directly t
4 min read
How to Build a Simple and Scalable Web API using Nest.js and Typescript ?
NestJS is a progressive Node.js framework that leverages TypeScript and is built on top of Express.js. It’s designed to provide an application architecture out of the box, which helps to create highly testable, maintainable, and scalable applications. In this guide, we will walk through the steps to build a simple and scalable Web API using NestJS
5 min read
JSON Modify an Array Value of a JSON Object
The arrays in JSON (JavaScript Object Notation) are similar to arrays in JavaScript. Arrays in JSON can have values of the following types: nullbooleannumberstringarrayobject The arrays in JavaScript can have all these but it can also have other valid JavaScript expressions which are not allowed in JSON. The array value of a JSON object can be modi
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to Write Postman Test to Compare the Response JSON against another JSON?
In the era of API-driven development, testing the API responses to ensure their correctness is of paramount importance. One such test includes comparing the JSON response of an API against a predefined JSON. In this article, we will delve into how to write a Postman test for this purpose. Table of Content What is Postman?JSON and its Role in APIsWh
4 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solving this problem, which are discussed below: Table of Content Using JSON.parse() MethodUsing JavaScript eval() MethodUsing Function ConstructorU
4 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
Create a chart from JSON data using Fetch GET request (Fetch API) in JavaScript
In this article, we are going to create a simple chart by fetching JSON Data using Fetch() method of Fetch API. The Fetch API allows us to conduct HTTP requests in a simpler way. The fetch() method: The fetch method fetches a resource thereby returning a promise which is fulfilled once the response is available. Syntax: const response = fetch(resou
3 min read
How to create a REST API using json-server npm package ?
This article describes how to use the json-server package as a fully working REST API. What is json-server? json-server is an npm(Node Package Manager) module/package, used for creating a REST API effortlessly. Data is communicated in JSON(JavaScript Object Notation) format between client and server. Installation: Execute the below command in your
4 min read
How to add API function to a simple PHP Page ?
Application Programming Interface is a system that contains a set of rules or protocols or tools which help in providing interaction between two applications or software by standard data access. It is very much similar to a web service used in developing web pages or mobile apps. One application can call other programs API to utilize some functiona
4 min read
How to Sort JSON Object Arrays Based on a Key?
Sorting is the process of arranging elements in a specific order. In JavaScript, we can sort a JSON array by key using various methods, such as the sort() function. Along with this, we can use various other approaches and methods that are implemented in this article. Below are the approaches to sort JSON Object Arrays based on a Key: Table of Conte
3 min read
Make a Web-based Weather Report of your Location using OpenWeatherMap API
Follow these simple steps in order to make a Web-based Weather Application Using OpenWeatherMap API. Step 1: Make your account in OpenWeatherMap for accessing their API for our project. Create an Account. It's totally FREE. After making an account you will get a default key just note/copy that key because we will use it for our feature steps. Step
4 min read
How to build a simple Discord bot using Node.js ?
Discord is an instant messaging application mostly used by developers and gamer communities. Many discord servers use bots to automate the task. Bots are programs that allow us to automate some tasks like messaging, maintaining our server, etc. Discord provides us with many built-in bots. Discord also allows us to build our own bots. For javascript
3 min read
Simple Task Manager CLI using Node.js
Before creating a simple Task Manager CLI using NodeJS, let's run our first basic Node.js application with the following simple steps: Note: You can download and install the Node.js application from href="https://nodejs.org/en/" Step 1: Create a Directory for our Task Manager CLI named TODO-CLI, you can give the name of your choice. Step 2: In that
4 min read
How to return a JSON response from a Flask API ?
Flask is one of the most widely used python micro-frameworks to design a REST API. In this article, we are going to learn how to create a simple REST API that returns a simple JSON object, with the help of a flask. Prerequisites: Introduction to REST API What is a REST API? REST stands for Representational State Transfer and is an architectural sty
3 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Request Returns a List of all UsersPOST Request to c
4 min read
How to iterate over JSON object fetched from API in Angular ?
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. It is the replacement of the XML data exchange format. In this article, we will learn How to Iterate over JSON objects fetched from API in Angular. Installing & Configuring the Angula
3 min read
Article Tags :
Trending in News
- OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
- How to Merge Cells in Google Sheets: Step by Step Guide
- How to Lock Cells in Google Sheets : Step by Step Guide
- PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
- #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, check: true }), success:function(result) { jQuery.ajax({ url: writeApiUrl + 'suggestions/auth/' + `${post_id}/`, type: "GET", dataType: 'json', xhrFields: { withCredentials: true }, success: function (result) { $('.spinner-loading-overlay:eq(0)').remove(); var commentArray = result; if(commentArray === null || commentArray.length === 0) { // when no reason is availaible then user will redirected directly make the improvment. // call to api create-improvement-post $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id, }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); return; } var improvement_reason_html = ""; for(var comment of commentArray) { // loop creating improvement reason list markup var comment_id = comment['id']; var comment_text = comment['suggestion']; improvement_reason_html += `
${comment_text}
`; } $('.improvement-reasons_wrapper').html(improvement_reason_html); $('.improvement-bottom-btn').html("Create Improvement"); $('.improve-modal--improvement').hide(); $('.improvement-reason-modal').show(); }, error: function(e){ $('.spinner-loading-overlay:eq(0)').remove(); // stop loader when ajax failed; }, }); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ $('.improvement-reason-modal').hide(); } $('.improve-modal--improvement').show(); }); function loadScript(src, callback) { var script = document.createElement('script'); script.src = src; script.onload = callback; document.head.appendChild(script); } function suggestionCall() { var suggest_val = $.trim($("#suggestion-section-textarea").val()); var array_String= suggest_val.split(" ") var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(suggest_val.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `
${suggest_val}
`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-section-textarea').val(""); jQuery('.suggest-bottom-btn').css("display","none"); // Update the modal content const modalSection = document.querySelector('.suggestion-modal-section'); modalSection.innerHTML = `
Thank You!
Your suggestions are valuable to us.
You can now also contribute to the GeeksforGeeks community by creating improvement and help your fellow geeks.
`; }, error:function(data) { jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 5 Words and Maximum Character limit is 2000."); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('#suggestion-section-textarea').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('#suggestion-section-textarea').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // load the captcha script and set the token loadScript('https://www.google.com/recaptcha/api.js?render=6LdMFNUZAAAAAIuRtzg0piOT-qXCbDF-iQiUi9KY',[], function() { setGoogleRecaptcha(); }); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.improvement-reason-modal').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { $('.spinner-loading-overlay:eq(0)').remove(); var result = e.responseJSON; if(result.detail.non_field_errors.length){ $('.improve-modal--improve-content .improve-modal--improve-content-modified').text(`${result.detail.non_field_errors}.`); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); $('.improvement-reason-modal').hide(); } }, }); });
Continue without supporting 😢