How to Create Basic API in Node JS Express?
Hi,
Now, let's see article of how to create api in node js. We will look at example of how to create api in node js express. you can understand a concept of node js create api example. if you have question about create simple api using node js then i will give simple example with solution.
Here, i will give you very simple example how to create simple api in node js with express. we will create "users" api and return users.json file data. so let's follow bellow step to create simple example
Step 1: Create Node App
run bellow command and create node app.
mkdir my-app
cd my-app
npm init
Install Express using bellow command:
npm install express --save
Step 2: Create server.js file
Here, we will create simple users api with GET method.
server.js
const express = require('express')
const fs = require('fs')
const app = express()
app.get('/', (req, res) => {
res.end('Hello World!, Example from ItSolutionstuff.com');
});
app.get("/users", (req, res) => {
fs.readFile(__dirname + '/' + 'users.json', 'utf8', (err, data) => {
res.end(data);
});
});
app.listen(3000, () => {
console.log(`app listening at //localhost:3000`)
});
Now let's create users.json file as bellow:
users.json
[
{
"id": 1,
"name": "Hardik",
"email": "hardik@gmail.com"
},
{
"id": 2,
"name": "Vimal",
"email": "vimal@gmail.com"
},
{
"id": 3,
"name": "Harshad",
"email": "harshad@gmail.com"
}
]
now you can simply run by following command:
node server.js
Output:
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Copy File to Another Directory in Node JS?
- How to Generate QR Code in Node JS?
- How to Get Client IP Address in Node JS?
- How to Get Query String Value in Node.js?
- Node JS Express Route with Parameters Example
- Node JS Find and Update Object in Array Example
- Node JS Foreach Loop Array Example
- How to Create and Use .env File in Node JS?
- Node JS Http Request with Headers Example
- Node JS Make HTTP Put Request Example
- Laravel Sanctum SPA API Authentication Example
- Laravel 8 REST API with Passport Authentication Tutorial