Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a REST Application in node.js with Express

DZone's Guide to

Creating a REST Application in node.js with Express

Learn how to create a REST API in node.js using the express framework.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

In this article you will see how it is easy to create a REST API in node.js using the express framework. The prerequisites for this tutorial is a basic knowledge on node.js, and basic understanding of REST architecture. You don't need any express knowledge.

We begin with creating the node application folder first, our application name would be share so does the folder name.

$ mkdir share
$ cd share

Now we can create our node application using npm init command.

$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (share) 
version: (1.0.0) 
description: Sample RestApi
entry point: (index.js) app.js
test command: 
git repository: 
keywords: 
author: dursun
license: (ISC) 
About to write to /Users/dursun/workspaces/dzone/myArt/share/package.json:

{
  "name": "share",
  "version": "1.0.0",
  "description": "Sample RestApi",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "dursun",
  "license": "ISC"
}


Is this ok? (yes) yes

Next step is to add the express framework and body-parser to our project.

$ npm install express --save
npm WARN package.json share@1.0.0 No repository field.
npm WARN package.json share@1.0.0 No README data
express@4.13.3 node_modules/express
├── escape-html@1.0.2
├── merge-descriptors@1.0.0
├── cookie@0.1.3
├── array-flatten@1.1.1
├── cookie-signature@1.0.6
├── utils-merge@1.0.0
├── content-type@1.0.1
├── vary@1.0.1
├── range-parser@1.0.2
├── content-disposition@0.5.0
├── fresh@0.3.0
├── path-to-regexp@0.1.7
├── serve-static@1.10.0
├── methods@1.1.1
├── etag@1.7.0
├── parseurl@1.3.0
├── depd@1.0.1
├── qs@4.0.0
├── on-finished@2.3.0 (ee-first@1.1.1)
├── finalhandler@0.4.0 (unpipe@1.0.0)
├── debug@2.2.0 (ms@0.7.1)
├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1)
├── accepts@1.2.13 (negotiator@0.5.3, mime-types@2.1.7)
├── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.7)
└── send@0.13.0 (destroy@1.0.3, statuses@1.2.1, ms@0.7.1, mime@1.3.4, http-errors@1.3.1)
$ npm install body-parser --save 
npm WARN package.json share@1.0.0 No repository field.
npm WARN package.json share@1.0.0 No README data
body-parser@1.14.0 node_modules/body-parser
├── bytes@2.1.0
├── content-type@1.0.1
├── depd@1.1.0
├── qs@5.1.0
├── iconv-lite@0.4.11
├── on-finished@2.3.0 (ee-first@1.1.1)
├── http-errors@1.3.1 (statuses@1.2.1, inherits@2.0.1)
├── raw-body@2.1.3 (unpipe@1.0.0)
├── debug@2.2.0 (ms@0.7.1)
└── type-is@1.6.8 (media-typer@0.3.0, mime-types@2.1.7)


Before we start coding lets have a look at our package.json file, it should be as follows;

{
  "name": "share",
  "version": "1.0.0",
  "description": "Sample RestApi",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "dursun",
  "license": "ISC",
  "dependencies": {
    "express": "^4.13.3"
  }
}

Now it is time to create our entry application file app.js, 

var express = require('express'),
bodyParser  = require('body-parser');

var app = express();

app.use(bodyParser.json());

var shareRouter = express.Router();

var db = [];

shareRouter.route('/')
    .get(function(req, res) {
    res.status(200).json(db);
    })
    .post(function(req,res){
    db.push(req.body);
    res.status(200).json(db);
    });


app.use('/api/share', shareRouter);

app.listen(8080, function(){
console.log('Application started.');
})

module.exports = app;

At line 1 and 2, included frameworks, at line 4, created express application, and at line 24 the application has started listening.

From line 6 to 22, the application is configured. At line 22 we routed all of the requests made on the url '/api/share' to the shareRouter. The shareRouter handles both get, and the post requests for the get requests we simply return the db object. For the post requests we added the object provided in the body. by the way the body of the post request is parsed into json by the express middleware body-parser which is added at line 6.

Start application and test api:

$ node app.js
Application started.

We will use postman to test our api as follows;

First Get

post

Get Final



Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
nodejs ,expressjs ,rest api ,rest api services ,express.js

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}