You are on page 1of 12

Make API call in NodeJS

STEP - 1:
All Http Methods:

1: POST (create a resource or generally provide data)


2: GET (retrieve an index of resources or an individual resource)
3: PUT (create or replace a resource)
4: PATCH (update/modify a resource)
5: DELETE (remove a resource)

STEP - 2:
Install NodeJS server in system:

For Linux:
Open your terminal write below command
sudo apt install nodejs

For Window:
Go through below documentation
https://phoenixnap.com/kb/install-node-js-npm-on-windows

For Mac:
Open your terminal write below command
brew update
brew install node

Now check your version by write command on your terminal:


node -v

STEP - 3:
Environment Setup:
1​: Create a folder “Demo”
2​: Make file ​server.js
3​: Open folder with VS code or any other code editor and open terminal in VS code.
4​: Write command:
​ ​npm init
After that enter and you see some points which are given below in which
you can skip by press enter or (you can give description in some place):
● ​package name: (Demo)
Your package name is basically your folder name (if you remember we put our folder name id
“Demo” press enter button)

● version: (1.0.0)
You have show your latest version press enter button

● Description: Make API call (​Here I give description “Make API call” you can give your own
description and press enter button.​)

● entry point: (server.js) (​It shows your entry point. press enter button​)

● test command: (​Skip it by press enter button​)

● git repository: (​Skip it by press enter button​)

● keywords: (​Skip it by press enter button​)

● author: demo file (​You can give your name or any other name or you can skip by press enter
button​)
● license: (​Skip it by press enter button​)

After pressing the enter button you see “Is this Ok: (yes)” you can press enter. Now you
can see ​package.json​ is automatically created in your folder.
In this file you can see your scripts and here all dependencies.
5​. Now start writing below code on ​server.js ​ firstly we create a server with node http
method.

const http = require(“http”)


const server = http.createServer((req, res) => {
res.write(“Hello I am running on localhost:5000”)
res.end()
})

Create PORT of the server


const PORT = 5000 (you can write your PORT)

server.listen(PORT, () => console.log(`Your server is running on port ${PORT}`))

6​.Start node server by using ​npm start​. And open postman and hit the url
localhost:5000/ ​and you can get “​Hello I am running on localhost:5000​” in response
body, If you can not get your response then you do something wrong.

STEP - 4:
Make API with MVC pattern:
Node http method is deprecated now, so now we create a new server using expressJS
framework. Now you can install some node modules write these command in VS code
terminal which are given below:
● npm install -D nodemon
● npm install express

Now we can move forward and start making API. We can follow MVC pattern for making
API, so that we can create some folders which are given below.
● models
● routes
● Controller
models​: We can create our database schema in the models folder.

Create a ​Person.js​ (​In models folder all files start with capital letter)​ file in the models folder.
Because I do not use any database in this section so I take a Person array in which
create two objects initially hard coded. And exports a Person array.

Person​ = [
{
​name:​ ​"Amit",

​age:​ 2
​ 5,

​id:​ 1
​ ,

},
{
​name:​ ​"krishna"​,
​age:​ 2
​ 2,

​id:​ 2
​ ,

},
];

module​.e
​ xports​ = ​Person;

route​: In route we can define our API url which are added after ​localhost:5000/ ​ and call
the functions which are defined in our controller folder. Some steps are followed for
create routes.
Create a person.js file in the route folder. We start with creating two routes, the url are
same but the methods are differents (​Remember I talk about https method in ​step 1​)
a.​ Firstly we use a ​post​ ​method​ for creating a new person in the ​models Person
array​.
b​. Second we use a ​get​ ​method​ for fetching all persons from the ​models Person
array​.

i.​ For that firstly we import express.


Ii. ​Now I extract router function from express
const router = express.Router()
Iii.​ Now pass url in route and function in method and also import these functions from
controller folder.
router.route(“/api/”)​.get(getAllPersons).post(createNewPerson)
iv. ​Now export the router function.
module.exports = router;
controller​: In the controller folder we can create different functions which are called on
different urls from router person.js file.

Create a ​person.js file in the controller folder​. And define all functions which are
imported in the ​route person.js folder.

a.​ import Person array from models


const Person = require(“../models/Person.js”)
b.​ Make getAllPersons function.

c.​ Make createNewPerson function.

STEP - 4:
Make some changes in server.js file:

i.​ In ​server.js​ file, delete all previous things. Now import express in server.js
const express = require("express");
ii.​ Import ​route person.js​ file from route folder
Const persons = require(“./route/person”)

iii. ​Extract express function from express


const app = express()

iv.​ Use the json parser function in app which helps to parse json data.
app.use(express.json())

v. ​Pass base url and imported ​route person.js ​in app.use because when url
hit it find and call right function.
app.use(“/persons”, persons)

vi. ​Set your PORT in which your server will be run


const PORT = 5000

Vii. ​Add an app listener which listens by the server and read the url and
fetches data accordingly.
app.listen(PORT, () => console.log(`See Running port ${PORT}`))
Now our all setup is ready now you will run your sever by using ​npm start
command in your terminal, now your see your server in running on port:
5000.
Now open your POSTMAN software.

i. POST REQUEST:
url: ​http://localhost:5000/persons/api
body:​ {
“name”: “demo”,
“Age”: 99,
“id” : 3
}
Headers: “Content-Type” : “application/json”

a. ​Put the url on the postman search browser, select your method
and put. I selected the POST method for creating a new person.
b. ​Now click on Headers option which has shown below the browser
box, and add one header “Content-type” : “application/json” in
headers option.

c. ​Now click on the ​Body​ option, now select on raw option and select json
type and write person details in body in json form, and click on the s ​ end
button​.
{
"name": "Ravi",
"age": 23,
"id": 3
}
d.​ Now you will see your response in the response block which is at the
bottom on the in postman. If response is OK with status code 200 means you
have created the person successfully. In response you get a created
person.

i. GET REQUEST:
url: ​http://localhost:5000/persons/api
body:​ no body required.
Headers: ​no external headers required in Get method.

a. ​The Get method url is the same as the Post method url, but we need to
change the method. So, click on the method dropdown and select Get method.
Because body is not required in the Get method, so change the “none”
option with “raw” body.

b. ​Now click on the ​send button​.


c. ​You can get all persons array in json form in response block with
status code 200 which is shown in the success part​.

You Can Create More Route For Update and Delete, Which I
tell you in the coming section.

You might also like