A REST API, or Representational State Transfer API, is a web service that uses HTTP requests to GET, PUT, POST, and DELETE data. In this tutorial, we’ll be using Node.js and Express to create a CRUD API.
First, we’ll create a new project using the npm init command. We’ll also need to install Express and body-parser.
npm init
npm install express body-parser
Next, we’ll create a file called index.js and require the Express and body-parser modules.
var Express = require ( ‘express’ );
var bodyParser = require ( ‘body-parser’ );
Next, we’ll create a new Express app and use the bodyParser middleware to parse incoming POST and PUT requests.
var app = Express ();
app . use ( bodyParser . urlencoded ({ extended : true }));
Next, we’ll create a route for our API. We’ll use the GET method to retrieve data and the POST, PUT, and DELETE methods to create, update, and delete data.
app . get ( ‘/’ , function ( req , res ) {
res . send ( ‘Hello World!’ );
});
app . post ( ‘/’ , function ( req , res ) {
res . send ( ‘Hello World!’ );
});
app . put ( ‘/’ , function ( req , res ) {
res . send ( ‘Hello World!’ );
});
app . delete ( ‘/’ , function ( req , res ) {
res . send ( ‘Hello World!’ );
});
Finally, we’ll start the Express app and open the URL in a browser.
app . listen ( 3000 , function () {
console . log ( ‘API is running on port 3000!’ );
});