NodeJs/Express RestAPIs – POST/GET/PUT/DELETE requests

In the tutorial, we’re gonna look at way to create NodeJs/Express RestAPIs with Post/Get/Put/Delete requests.

Related posts:
How to setup Node/Express development environment

Goal

We create a NodeJs/Express RestAPIs project that has structure as below:

nodejs express - restapis - project structure

The project create a set of Rest-APIs for POST/GET/UPDATE/DELETE APIs:

  • ‘/api/customers’ – GET all customers
  • ‘/api/customers/:id’ – GET a customer by Id
  • ‘/api/customers’ – POST a customer
  • ‘/api/customers/update/:id’ – UPDATE a customer by Id
  • ‘/api/customers/delete/:id’ – DELETE a customer by Id

Setup NodeJs/Express project

Use NPM to create a Node/Express project as the guide

Create application directory

Create package.json file

Use the npm init to create ‘package.json’ file:

-> Check content of ‘package.json’ file:

Install Express & Body-Parser

We need express and body-parse modules.
– Express is one of the most popular web frameworks for NodeJs which is built on top of Node.js http module, and adds support for routing, middleware, view system etc.
– Body-parser: parses/extract the body of an incoming HTTP request.

-> Installing them as commandline npm install express body-parser --save:

Now see ‘package.json’ file:

nodejs express - restapis - project structure - when install express and body-parser

Implement NodeJs/Express RestApis

Create server

In root folder ‘nodejs-restapi’, create a ‘server.js’ file:

Implement Express Application
Routes

In root folder ‘nodejs-restapi’, create a router folder ‘/app/routes’. Then create a file ‘/app/routes/customer.routes.js’ for routing requests ‘GET/POST/DELETE/UPDATE’:

Controllers

In root folder ‘nodejs-restapi’, create a controller folder ‘/app/controllers’. Then create a file ‘/app/controllers/customer.controller.js’ that contains methods for executing above URL requests:

Now see again the project structure:

nodejs express - restapis - project structure

Test results

Run the NodeJs/Express project:

Use Postman to check result ->

– GET all customers:

nodejs express - restapis - project structure - get all

– GET a customer by id:

nodejs express - restapis - project structure - get by id

– POST a customer:

nodejs express - restapis - project structure - post customer

– PUT a customer:

nodejs express - restapis - project structure - put customer

– DELETE a customer:

nodejs express - restapis - project structure - delete customer

-> NodeJs/Express Logs:

Sourcecode

Nodejs-RestAPIs

By JavaSampleApproach | April 6, 2018.

Related Posts


Got Something To Say:

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

*