How to create REST API in Nodejs?
Tags: node, api
Published: 2021-09-16 02:47:11

**A REST API (Web API)** is an application programming interface that allows us for interaction with RESTful web services or app services. REST stands for representational state transfer. It was created by computer scientist Roy Fielding. Here we will create REST API in Nodejs.

**It uses HTTP requests to access and use data. The most common HTTP requests are GET, POST, PUT, DELETE.**

##REST API is useful in
1. Web Services
2. App Services
3. Cross Platform Applications
4. Cloud Applications
5. Stateless Applications
6. Communicate different devices or platforms

##REST API supports the Data formats
* application/json
* application/xml
* multipart/form-data
* application/x-wbe+xml
* application/x-www-form-urlencoded

##Securing REST APIs
* Using HTTPS
* Blocking access from unknown IP addresses and domains
* Validating Input and Output
* Blocking unexpectedly large payloads
* Logging requests
* Investigating failures
* Sending Status Codes like 200,400 etc
* Validating Clients and Devices
* Authorizing API
* Authenticate URLs
* Using Headers Authorization

#Create REST API in Nodejs
**Step1 :** Create a folder database in root directory and create a file users.json. Paste the code given below.

```php
{
	"user1" : {
		"id" : 1,
		"name" : "Chetan"
	}
}
```

**Step 2 :** Create a file api.js and paste the code given below.

```php
var express = require("express");
var app = express();
var fs = require('fs');

/*get api*/

app.get('/list-users', function(req, res){
	fs.readFile(__dirname+'/database/users.json','utf8', function(err,data){
		res.end(data);
	});
});

/*post api*/
app.post('/create-user', function(req,res){

	fs.readFile(__dirname+'/database/users.json', 'utf8', function(err,data){
		data = JSON.parse(data);
		data["user2"] = {'id' : 2, "name": "Pankaj"};
		data = JSON.stringify(data);
		fs.writeFile(__dirname+'/database/users.json', data,function(res){
			console.log(res);
		});
		res.end(data);
	});

});

/*delete data*/

app.delete('/delete-user/:id', function(req, res){
	fs.readFile(__dirname+'/database/users.json', function(err,data){

		data = JSON.parse(data);
		
		delete data['user'+req.params.id];

		data = JSON.stringify(data);

		fs.writeFile(__dirname+'/database/users.json',data,function(res){
			console.log(res); //it is error response
		});

		res.end(data);

	});
});

/*create server*/

var server = app.listen(8081, function(){
	var host = server.address().address;
	var port = server.address().port;
	console.log('Server Running at http://%s:%s',host,port);
});
```

**Step 3 :** Install Express Node Package

Use these commands one by one

```php
npm install express --save
npm install body-parser --save
npm install cookie-parser --save
npm install multer --save
```

**Step 4 :** Now run Node.js application
Use this command to run

```php
node api.js
```

**Step 5 :** To test the api run the following URLs

localhost:8081/list-users

localhost:8081/create-user

localhost:8081/delete-user/1

You can replace localhost with your domain or IP

[![How to Create REST API in Node Js](http://img.youtube.com/vi/B7WTDLUOLi4/0.jpg)](http://www.youtube.com/watch?v=B7WTDLUOLi4)

####See the Video

___
###See Also
[How to Create Multiple Parameters Dynamic Routes in Laravel](https://www.w3courses.org/how-to-create-multiple-parameters-dynamic-routes-in-laravel/)

[Laravel 8 Multiple Database and Resource Routes with Controllers](https://www.w3courses.org/laravel-8-multiple-database-and-resource-routes-with-controllers/)

[Optimize Database Queries in Laravel](https://www.w3courses.org/how-to-optimize-database-queries-in-laravel/)

[Flash Messages in AngularJS](https://www.w3courses.org/flash-messages-in-laravel-with-angular-material/)

[Create Filters in AngularJS](https://www.w3courses.org/create-filters-in-angularjs/)
___

**Thanks For Reading :)**

**Please give your comments :)**

**Please Must Visit My Website :)**

[W3Courses](https://www.w3courses.org)