Creating Rest API in Node Js

|
| By Webner

Rest API

Rest API is an application program interface, that uses GET, POST, PUT, DELETE data. It is referred to as a REPRESENTATIONAL STATE TRANSFER (RESTful) web service.

Creating the API

Creating Rest API in Node Js firstly needs to make a directory(mkdir restfulapi) to create a project and then install Node using npm init. Then type the name of the project, version, author, description, main(index.js). After adding, the information automatically gets package.json file which contains information in JSON format.
rest api 1
rest api 2
Using $ npm install express command, install node_module in the project folder. Now install express package. After that, create a file for server(server.js) configuration.
const http = require('http');
const app = require('./app');
const port = 3001;
const server = http.createServer(app);
server.listen(port);

Create a file app.js use the express, using use middleware pass the 200 status or data in json format. In the end, pass the app argument to the module.

const express = require('express');
const app = express();
app.use((req,res,next)=>{
res.status(200).json({
message: 'it works !!'
});
});
module.exports = app;

After that, check the http://localhost:3001/ hitting the browser and also on the postman using the GET parameter. Now get the response.

{
"message": "it works !!"
}

response

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *