Build A Node.js API in 2 Minutes.

Rhea RB
2 min readDec 23, 2022

--

What is an API ?
API stands for Application Programming Interface. In APIs, the word Application refers to any software with a different function. Interface can be considered as a contract between two applications. This contract defines how the two communicate with each other using requests and responses.

Lets’ begin building our own API …

Download Node.js.
First we need to setup a Nodejs server. For this purpose download and install node.js from its official website.

Setup Project

  1. Create a directory.
  2. Open it in your preferred code editor.
  3. Run the following command in your terminal to create package.json.
npm init -y 

Adding Script

Update the scripts inside package.json with the following.

"scripts": {
"start": "node index.js"
}

Install Express package.

Run the below command in the project terminal to install Express in the project.

npm install express

Creating a route

Create a file named index.js. Here we will write the country route.

const express = require ('express');
const app = express();

app.get('/country', (req,res)=> {
res.send([
{
id: 1,
name: 'USA'
},
{
id: 1,
name: 'UK'
}
])
});

let port = 8088;

app.listen(port, ()=> {
console.log('Server started on ' + port);
})

Code Explanation.

  1. First we imported the package express
  2. We created an express app by initiating express().
  3. We created a route /country and attached a function to it. We any user calls the GET method, the function will get executed.
  4. Lastly we run express on a port, 8088 in this case.

Run the API.

Run the below command on your terminal.

npm start

Test the API.

We use Postman to test the api. You can also use RapidAPI client a VS code extension.

And It works !!

If you liked my blog, please do follow me on

Thank you for Reading ! Happy Coding !

--

--

Rhea RB

Hello ! I am a senior software engineer, passionate about tech and product.