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
Overview
Demo
Goal
We create a NodeJs/Express RestAPIs project that has structure as below:
/nodejs-restapi /app /controllers customer.controller.js /routes customer.routes.js /node-modules package.json package-lock.json server.js
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
mkdir nodejs-restapi cd nodejs-restapi
Create package.json file
Use the npm init
to create ‘package.json’ file:
nodejs-restapi>npm init ... Press ^C at any time to quit. package name: (nodejs-restapi) version: (1.0.0) description: NodeJs-RestApis entry point: (index.js) server.js test command: git repository: keywords: NodeJs-RestAPIs author: JSA license: (ISC) About to write to C:\Users\pc\Desktop\nodejs\nodejs-restapi\package.json: { "name": "nodejs-restapi", "version": "1.0.0", "description": "NodeJs-RestApis", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "NodeJs-RestAPIs" ], "author": "JSA", "license": "ISC" } Is this ok? (yes) yes
-> Check content of ‘package.json’ file:
{ "name": "nodejs-restapi", "version": "1.0.0", "description": "NodeJs-RestApis", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "NodeJs-RestAPIs" ], "author": "JSA", "license": "ISC" }
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
:
nodejs-restapi>npm install express body-parser --save npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN nodejs-restapi@1.0.0 No repository field. + body-parser@1.18.2 + express@4.16.3 added 53 packages in 12.449s
Now see ‘package.json’ file:
{ "name": "nodejs-restapi", "version": "1.0.0", "description": "NodeJs-RestApis", "main": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [ "NodeJs-RestAPIs" ], "author": "JSA", "license": "ISC", "dependencies": { "body-parser": "^1.18.2", "express": "^4.16.3" } }
Implement NodeJs/Express RestApis
Create server
In root folder ‘nodejs-restapi’, create a ‘server.js’ file:
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.json()) require('./app/routes/customer.routes.js')(app); // Create a Server var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("App listening at http://%s:%s", host, port) })
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’:
module.exports = function(app) { var customers = require('../controllers/customer.controller.js'); // Create a new Customer app.post('/api/customers', customers.create); // Retrieve all Customer app.get('/api/customers', customers.findAll); // Retrieve a single Customer by Id app.get('/api/customers/:id', customers.findOne); // Update a Customer with Id app.put('/api/customers/:id', customers.update); // Delete a Customer with Id app.delete('/api/customers/:id', customers.delete); }
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:
var customers = { customer1: { firstname: "Jack", lastname: "Davis", age: 25, id: 1 }, customer2: { firstname: "Mary", lastname: "Taylor", age: 37, id: 2 }, customer3: { firstname: "Peter", lastname: "Thomas", age: 17, id: 3 }, customer4: { firstname: "Peter", lastname: "Thomas", age: 17, id: 4 } } exports.create = function(req, res) { var newCustomer = req.body; customers["customer" + newCustomer.id] = newCustomer; console.log("--->After Post, customers:\n" + JSON.stringify(customers, null, 4)); res.end("Post Successfully: \n" + JSON.stringify(newCustomer, null, 4)); }; exports.findAll = function(req, res) { console.log("--->Find All: \n" + JSON.stringify(customers, null, 4)); res.end("All Customers: \n" + JSON.stringify(customers, null, 4)); }; exports.findOne = function(req, res) { var customer = customers["customer" + req.params.id]; console.log("--->Find customer: \n" + JSON.stringify(customer, null, 4)); res.end( "Find a Customer:\n" + JSON.stringify(customer, null, 4)); }; exports.update = function(req, res) { var id = parseInt(req.params.id); var updatedCustomer = req.body; if(customers["customer" + id] != null){ // update data customers["customer" + id] = updatedCustomer; console.log("--->Update Successfully, customers: \n" + JSON.stringify(customers, null, 4)) // return res.end("Update Successfully! \n" + JSON.stringify(updatedCustomer, null, 4)); }else{ res.end("Don't Exist Customer:\n:" + JSON.stringify(updatedCustomer, null, 4)); } }; exports.delete = function(req, res) { var deleteCustomer = customers["customer" + req.params.id]; delete customers["customer" + req.params.id]; console.log("--->After deletion, customer list:\n" + JSON.stringify(customers, null, 4) ); res.end( "Deleted customer: \n" + JSON.stringify(deleteCustomer, null, 4)); };
Now see again the project structure:
Test results
Run the NodeJs/Express project:
nodejs-restapi>node server.js App listening at http://:::8081
Use Postman to check result ->
– GET all customers:
– GET a customer by id:
– POST a customer:
– PUT a customer:
– DELETE a customer:
-> NodeJs/Express Logs:
App listening at http://:::8081 --->Find All: { "customer1": { "firstname": "Jack", "lastname": "Davis", "age": 25, "id": 1 }, "customer2": { "firstname": "Mary", "lastname": "Taylor", "age": 37, "id": 2 }, "customer3": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 3 }, "customer4": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 4 } } --->Find customer: { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 3 } --->After Post, customers: { "customer1": { "firstname": "Jack", "lastname": "Davis", "age": 25, "id": 1 }, "customer2": { "firstname": "Mary", "lastname": "Taylor", "age": 37, "id": 2 }, "customer3": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 3 }, "customer4": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 4 }, "customer5": { "firstname": "Adam", "lastname": "Johnson", "age": 48, "id": 5 } } --->Update Successfully, customers: { "customer1": { "firstname": "Jack", "lastname": "Davis", "age": 25, "id": 1 }, "customer2": { "firstname": "Mary", "lastname": "Taylor", "age": 37, "id": 2 }, "customer3": { "firstname": "Peter", "lastname": "Thomas", "age": 28, "id": 3 }, "customer4": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 4 }, "customer5": { "firstname": "Adam", "lastname": "Johnson", "age": 48, "id": 5 } } --->After deletion, customer list: { "customer2": { "firstname": "Mary", "lastname": "Taylor", "age": 37, "id": 2 }, "customer3": { "firstname": "Peter", "lastname": "Thomas", "age": 28, "id": 3 }, "customer4": { "firstname": "Peter", "lastname": "Thomas", "age": 17, "id": 4 }, "customer5": { "firstname": "Adam", "lastname": "Johnson", "age": 48, "id": 5 } }