Skip to content

P: +1 (800) 799 8545

E: qatcommunications@qat.com

  • Client Portal
  • Employee Portal

P: +1 (800) 799 8545 | E: sales[at]qat.com

QAT Global
  • What We Do

    Custom Software Development

    We build custom software with Quality, Agility, and Transparency to drive your business success.

    Engagement models.

    Access onshore and nearshore custom software development experts with engagement models tailored to fit your project needs.

    IT Staffing

    Client-Managed Teams

    Managed Teams

    Services

    Artificial Intelligence (AI)

    Cloud Computing

    Mobile Development

    DevOps

    Software Modernization

    Internet of Things (IOT)

    UI/UX

    QA Testing & Automation

    Technology Consulting

    Software Development

    View all >

    Technologies

    Agile

    AI

    AWS

    Azure

    DevOps

    Cloud Technologies

    Java

    JavaScript

    Mobile

    .NET

    View all>

    Industries

    Tech & Software Services

    Utilities

    Transportation & Logistics

    Payments

    Manufacturing

    Insurance

    Healthcare

    FinTech

    Energy

    Banking

    View all >

  • Our Thinking
    • QAT Insights Blog
    • Tech Talks
    • Resource Downloads
    • Case Studies
  • Who We Are
    • About QAT Global
    • Meet Our Team
    • Our Brand
  • Careers
  • Contact Us
Let’s Talk
QAT Global - Your Success is Our Mission
  • Ways We Help
    • Custom Software Development
    • IT Staffing
    • Dedicated Development Teams
    • Software Development Outsourcing
    • Nearshore Software Development
  • ServicesCustom Software Development Services Solutions Built to Fuel Enterprise Success and Innovation Explore QAT Global’s custom software development services, offering tailored solutions in cloud, mobile, AI, IoT, and more to propel business success.
  • Technology Expertise
  • Industries We ServeInnovate and Lead with Our Industry-Specific Expertise Leverage our targeted insights and technology prowess to stay ahead in your field and exceed market expectations.
  • What We Think
    • QAT Insights Blog
    • Downloads
  • Who We Are
    • About QAT Global
    • Meet Our Team
    • Omaha Headquarters
    • Careers
    • Our Brand
  • Contact Us

QAT Insights Blog > Simple REST Service with Node.js and Express

QAT Insights

Simple REST Service with Node.js and Express

Bonus Material: Free E-Book - The Ultimate Guide to Project Outsourcing

3.6 min read| Last Updated: January 9, 2025| Categories: Technical & Development|

Simple REST Service with Node.js and Express

Introduction

This is a simple tutorial showing how to create a REST service with Node.js using Express. This first tutorial will assume you have already installed Node.js, but it will walk you through installing Express and setting up a project. We will also show how to setup a simple REST service and how you can test it. In follow-up tutorials, we will show how to add a web page interface for interacting with the service, add authentication to the service and how to integrate with MongoDB for persistence.
If you are unfamiliar with Node.js, please visit their official website. Express is a web application framework for node.js, more info here.
The code for this tutorial is available here on github.

Setup The Environment

If you don’t already have express installed, you can install it with the following command:

npm install express -g 

You will want to create a new directory for your project, so create your project directory and then from within that directory, run the following command to create your new project shell.

express

The express command generates a project using the jade template engine. Before we can run the project, we first need to install the dependencies. To install the dependencies, run the following command:

npm install -d 

This command will download and install all of the dependencies into your project. You can now run your application and point your browser to https://localhost:3000, but it’s just an empty shell right now, next we will create the code for the service. To run your project in its current state, use the command:

node app.js 

Coding The Service

In our project directory we are going to create two new files in addition to the existing app.js, userManager.js and userProvider-array.js. The userManager.js will be our service and the userProvider-array.js will be our data layer that provides a user list to the service. Right now the userProvider is based on a javascript array and has no persistence, in future tutorials we will add persistence with mongodb.
Let’s start by taking a look at the userProvider-array.js file:

var nextUserId = 1;

UserProvider = function() {
  this.users = [];
  
  this.fetchAllUsers = function(cb) {
    cb(null, this.users);
  };
  
  this.fetchUserById = function(id, cb) {
    var foundUsers = this.users.filter(function(user) {return user._id == id});

    if (foundUsers.length == 0) {
      cb('User not found', null);
    } else {
      cb(null, foundUsers[0]);
    }
  };
  
  this.insertUser = function(user, cb) {
    user._id = nextUserId++;
    this.users.push(user);

    cb(null, user);
  };
  
  this.updateUser = function(user, cb) {
    this.fetchUserById(user._id, function(error, _user) {
      if (error) {
        cb(error, null);
      } else {
        _user.name = user.name;
        _user.city = user.city;
        _user.state = user.state;
    
        cb(null, _user);
      }
    });
  };
  
  this.deleteUser = function(id, cb) {
    this.users = this.users.filter(function(user) {return user._id != id});
    cb(null, {_id:id});
  };
};

exports.UserProvider = UserProvider;

Here we have created a UserProvider class with several methods for accessing a list of users.

  • fetchAllUsers – Fetches all users.
  • fetchUserById – Fetches a user by its _id property.
  • insertUser – Creates a user based on the given user object.
  • updateUser – Updates the details of a user by its _id property.
  • deleteUser – Deletes a user by its _id property.

Keeping with the spirit of node.js, everything is event driven, so you pass a callback method to each of these methods. It’s not really that necessary for this array based implementation but when we get to doing real I/O it will become very useful.
Next, we move on to the code for the userManager.js file, which is the actual service which will make use of this data provider.

UserManager = function(app) {
  var UserProvider = require('./userProvider-array').UserProvider;
  var userProvider = new UserProvider();

  userProvider.insertUser({_id:1, name:'Rocky', city:'Omaha', state:'NE'}, function(a,b){});
  userProvider.insertUser({_id:2, name:'Dave', city:'Stafford', state:'VA'}, function(a,b){});

  app.get('/users', function(req, res) {
    userProvider.fetchAllUsers(function(error, users) {
      res.send(users);
    });
  });

  app.post('/users', function(req, res) {
    userProvider.insertUser(req.body, function(error, user) {
      if (error) {
        res.send(error, 500);
      } else {
        res.send(user);
      }
    });
  });

  app.get('/users/:id', function(req, res) {
    userProvider.fetchUserById(req.params.id, function(error, user) {
      if (user == null) {
        res.send(error, 404);
      } else {
        res.send(user);
      }
    });
  });

  app.post('/users/:id', function(req, res) {
    var _user = req.body;
    _user._id = req.params.id;

    userProvider.updateUser(_user, function(error, user) {
      if (user == null) {
        res.send(error, 404);
      } else {
        res.send(user);
      }
    });
  });

  app.delete('/users/:id', function(req, res) {
    userProvider.deleteUser(req.params.id, function(error, user) {
      if (user == null) {
        res.send(error, 404);
      } else {
        res.send(user);
      }
    });
  });
};

exports.UserManager = UserManager;

This class has a constructor which takes the express app object. With this object we can add routes for the service. The first thing we do is create a new instance of UserProvider and then add a couple data rows to it. The methods for creating routes follow this basic design:

app.<http_method>(<url-path>, function(requestObject, responseObject) {

});

Finally, we wrap it all together by editing the app.js file so that it looks like this:

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

var UserManager = require('./userManager').UserManager;
var userManagerService = new UserManager(app);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

Now you can run your REST service and test it out by starting it with this command:

node app.js

Testing The Service

You are now ready to test your REST service, I would suggest using the Advanced Rest Client Chrome Plug-in. It’s an excellent free utility for testing REST services of all shapes and forms. Here is a screenshot of using it to test the very first fetchAllUsers method:
Advanced Rest Client Chrome Plug-in
Notice that we set https://localhost:3000/users as the URL for our fetchAllUsers request and we can see the following JSON response:

[
  {
    "_id": 1,
    "name": "Rocky",
    "city": "Omaha",
    "state": "NE"
  },
  {
    "_id": 2,
    "name": "Dave",
    "city": "Stafford",
    "state": "VA"
  }
]

We can also lookup users by their ID, such as https://localhost:3000/users/1, which produces:

{
    "_id": 1,
    "name": "Rocky",
    "city": "Omaha",
    "state": "NE"
}

Play around with the POST and DELETE methods to add/update and delete users from the array.
This concludes the first part of this tutorial, in the next tutorial we will change the array based provider to use MongoDB so that the storage is persistent.

Free E-Book - The Ultimate Guide to Project Outsourcing

Share This Story, Choose Your Platform!

Jump to Section:
  • Simple REST Service with Node.js and Express
    • Introduction
    • Setup The Environment
    • Coding The Service
    • Testing The Service
QAT Global - Your Success is Our Mission

At QAT Global, we don’t just build software—we build long-term partnerships that drive business success. Whether you’re looking to modernize your systems, develop custom solutions from scratch, or for IT staff to implement your solution, we’re here to help.

Your success is our mission.

BBB Seal

GoodFirms Badge - QAT Global - Omaha, NE

new on the blog.
  • AI Accelerated Software Development Services

    AI Accelerated Software Development Services

  • How QAT Global Achieved an 8× Software Delivery Acceleration with AI-Driven Workflows — And What It Means for Your Organization

    How QAT Global Achieved an 8× Software Delivery Acceleration with AI-Driven Workflows — And What It Means for Your Organization

  • The Essential Agentic Workflow Patterns Enterprises Use to Build Production-Ready AI Systems

    The Essential Agentic Workflow Patterns Enterprises Use to Build Production-Ready AI Systems

  • AI Data Quality Mistakes That Sabotage Your AI Strategy

    AI Data Quality Mistakes That Sabotage Your AI Strategy

ways we can help.
Artificial Intelligence
Custom Software Development
IT Staffing
Software Development Teams
Software Development Outsourcing
connect with us.
Contact Us

+1 800 799 8545

QAT Global
222 South 15th Street, Suite 405N
Omaha, NE 68102

(402) 391-9200
qat.com

follow us.
  • Privacy Policy
  • Terms
  • ADA
  • EEO
  • Omaha, NE Headquarters
  • Contact Us

Copyright © 2012- QAT Global. All rights reserved. All logos and trademarks displayed on this site are the property of their respective owners. See our Legal Notices for more information.

Page load link

Explore…

Services
  • Artificial Intelligence (AI)
  • Cloud Computing
  • Mobile Development
  • DevOps
  • Application Modernization
  • Internet of Things (IOT)
  • UI/UX
  • QA Testing & Automation
  • Technology Consulting
  • Custom Software Development
Our Work
  • Case Studies
Ways We Help
  • Nearshore Solutions
  • IT Staffing Services
  • Software Development Outsourcing
  • Software Development Teams
Who We Are
  • About QAT Global
  • Meet Our Team
  • Careers
  • Company News
  • Our Brand
  • Omaha Headquarters
What We Think
  • QAT Insights Blog
  • Resource Downloads
  • Tech Talks
Industries We Serve
  • Life Sciences
  • Tech & Software Services
  • Utilities
  • Industrial Engineering
  • Transportation & Logistics
  • Startups
  • Payments
  • Manufacturing
  • Insurance
  • Healthcare
  • Government
  • FinTech
  • Energy
  • Education
  • Banking
Technologies

Agile
Angular
Artificial Intelligence
AWS
Azure
C#
C++
Cloud Technologies
DevOps
ETL
Java
JavaScript
Kubernetes
Mobile
MongoDB
.NET
Node.js
NoSQL
PHP
React
SQL
TypeScript

QAT - Quality Agility Technology

Your Success is Our Mission!

Let’s Talk

Love this article? Don’t miss the next one!

Sign up for our newsletter for free guides, articles, and tips to power business and personal success.

This field is for validation purposes and should be left unchanged.
This field is hidden when viewing the form
Name
Consent(Required)
QAT Global

IT Staff Augmentation Success: A How-to Guide for Using an IT Staffing Agency

Get proven best practices for IT staff augmentation success. Learn how to use an IT staffing agency to source, vet, & support top tech talent.

Yes! I Want My Free E-Book
A How to Guide for Using an IT Staffing Agency
QAT Global

Ultimate Guide to Software Requirements Specifications

Gain expert insights into building effective SRS that help you avoid common pitfalls, streamline the development process, and deliver software that meets both stakeholder and user expectations.

Yes! I Want My Free E-Book
Software Requirements Specifications
QAT Global

Unlock the Secrets to Effective Team Management in the Age of Remote Work

This comprehensive guide is your key to fostering collaboration, boosting productivity, and achieving success in a remote work environment.

Yes! I Want My Free E-Book
Remote Work Team Management
QAT Global

The Ultimate Guide to Project Outsourcing

Discover The Power of Project Outsourcing For Business Success

Dive deep into the world of outsourcing and discover how it can be a game-changer for your business.

Yes! I Want My Free E-Book
Project Outsourcing
QAT Global

Unlock the Future of Mobile Technology

Discover how Progressive Web Apps are transforming enterprise mobility and bridging the gap between web and mobile.

Yes! I Want My Free E-Book
Mobile Revolution
QAT Global

Guide to Nearshore IT Staffing

Unlock Power of Nearshore IT Staffing Solutions

Discover cost-effective strategies and gain a competitive edge with expert nearshore staffing solutions.

Yes! I Want My Free E-Book
Nearshore IT Staffing Solutions
QAT Global

Guide to Strategic IT Staffing Solutions

Navigate the Future of IT Staffing with QAT Global

Explore the complexities and opportunities of IT staffing and learn about the evolution of IT staffing, the benefits of tailored solutions, and how QAT Global’s unique approach can help your organization thrive.

Yes! I Want My Free E-Book
Strategic IT Staffing Solutions
QAT Global

Strategic Nearshoring Guide

Transform Your Enterprise with Strategic Nearshoring

Discover how nearshore IT staffing drives agility, innovation, and cost efficiency in the digital age.

Yes! I Want My Free E-Book
Strategic Nearshoring Guide
QAT Global

Legacy Modernization Guide

What Are Your Legacy Systems Really Costing You?

Discover the hidden costs and unlock the potential of modernization for a more efficient and secure future.

Yes! I Want My Free E-Book
Legacy Modernization
QAT Global

Harness Innovation with Open Source Software

Discover how open source is revolutionizing enterprise organizations and driving digital transformation. Learn best practices for addressing security concerns, leveraging community collaboration, and navigating compliance.

Yes! I Want My Free E-Book
Open Source Software in Enterprise Organizations
QAT Global

Navigate the Ethical Implications of Big Data

Unlock insights from our executive briefing and learn strategies for addressing privacy concerns, maintaining ethical integrity, and navigating compliance in a data-driven world.

Yes! I Want My Free E-Book
Ethical Implications of Big Data
QAT Global

Achieve Business Growth Through Digital Transformation

Discover how top organizations are driving efficiency, improving customer experiences, and fueling growth with proven strategies for success.

Yes! I Want My Free E-Book
Digital Transformation