How to Create a REST API in NodeJS with Express
APIs (application programming interfaces) enable applications to communicate easily with each other, whether internally to connect different components throughout a website or externally as a service.
APIs such as these are great for security, code organization, and code reuse. Imagine you have a function that accepts a user ID, pulls data from a database using that unique identifier, and returns the associated data for that user. You wouldn't want to repeat this same function call throughout your code in each location you require user data.
A much cleaner and more sophisticated solution would be to create an API containing a single method. This method would return user data that you can access from anywhere and reuse throughout your website or application.
This article will walk you through this whole process by setting up a NodeJS REST API using the Express framework.
Prerequisites
Earlier, we talked about creating your first NodeJS webserver with the Express framework. You'll need to make sure you have NodeJS installed on your machine as well as the required dependencies to run a standard web server:
npm install express
npm install http
Additionally, you'll need to install the body-parser
package:
npm install body-parser
The body-parser
package is middleware designed to parse the body of the incoming requests. The resulting JSON string will consist of one or more key/value pairs we can use to access and manipulate data.
Quick Tip: You can simplify the npm package install process by combining all the package names into one line like so: npm install express http body-parser
Application Setup
In this NodeJS REST API example, we'll be managing a directory of users. Each user record will contain a first name, last name, and unique numeric identifier which will be used to manage each of the users individually.
Like our initial web server setup, we'll need to include the required packages and create an HTTP instance. This time, we'll also be including the body-parser
package to accept incoming JSON strings from the body of each request:
const express = require("express");
const app = express();
const body_parser = require("body-parser");
const http = require("http");
app.use(body_parser.json());
app.use(body_parser.urlencoded({ extended: false }));
var users = [];
http.createServer({}, app).listen(3000, function () {
// API methods go here
});
The users
array stores our current list of users but isn't generally how a real-world example of user management would work. Typically, users would be stored and managed in a database, including a relational database application like MySQL or SQL Server, for example. But this will give you a good idea of how the REST API works within NodeJS and how you can take it a step or two further.
Creating Our First User
First, we'll create a user by adding our first API method, user_add
, which will accept two parameters:
- first_name
- last_name
app.post("/user_add", function(req, res) {
var data = req.body;
if (data.first_name && data.last_name) {
var user = {
id: users.length + 1,
date: Date().toString(),
first_name: data.first_name,
last_name: data.last_name
};
users.push(user);
res.status(200).json({
message: "User created successfully!"
});
}
else {
res.status(401).json({
message: "Invalid user creation."
});
}
});
Here we start by defining this method as a POST
method of our application. The body contents of the request get assigned to the data
variable for use throughout the remainder of the function call.
A check is conducted to make sure all required parameters are present. If not, a 401 unauthorized response gets returned to the user, and the function call completed. If the parameters are present, we proceed by creating a user
object to store our parameter values and a few new variables. The new variables include:
id
: a numeric identifier for the userdate
: the date the user was added
Again, in a real-world example, we wouldn't assign an ID based on array size. The ID assignment is typically done automatically with database software using identity or unique identifier column types to prevent duplicates.
Do this a few times to add a few unique names to the list so we can test the next methods.
Calling All Users
Retrieving a list of all of our users is a pretty simple process. We'll create a GET
method called users_get
that returns the users array object in the response:
app.get("/users_get", function(req, res) {
res.status(200).json({
message: "Users pulled successfully!",
response: users
});
});
The output is as follows:
{
"message": "User pulled successfully!",
"response": [
{
"id": 1,
"date": "Tue Sep 10 2019 14:20:26",
"first_name": "Joe",
"last_name": "Shmo"
},
{
"id": 2,
"date": "Tue Sep 10 2019 14:20:31",
"first_name": "Foo",
"last_name": "Bar"
}
]
}
Returning a Single User Record
To return a single user record, we'll create a similar method. But this time we'll pass an ID parameter in the URL. The following function loops through our array of users and returns a single user if an ID matches:
app.get("/user_get/:id", function(req, res) {
var id = req.params.id;
for (var i = 0; i < users.length; i++) {
if (id == users[i].id) {
res.status(200).json({
message: "User pulled successfully!",
response: users[i]
});
}
}
res.status(401).json({
message: "User not found."
});
});
Passing a custom variable in a URL is slightly more complicated than a standard API call with no parameters. Each parameter must have a colon character prefix like our single user function call:
/user_get/:id
Each parameter key/value pair is accessible in the req.params
object and can be accessed by parameter name.
An empty user
object is created followed by a loop through the users
array to find the desired user by its associated ID. If the desired user exists, it's returned in the response.
{
"message": "User pulled successfully!",
"response": {
"id": 1,
"date": "Tue Sep 10 2019 14:34:07",
"first_name": "Joe",
"last_name": "Shmo"
}
}
If the user does not exist, a 401 error gets thrown.
Updating a User Record
For updating a user record, we'll create a PATCH
method, passing in a unique user ID through the URL like we did previously along with a few object values, first_name
and last_name
, to update in the request body:
app.patch("/user_update/:id", function(req, res) {
var id = req.params.id;
var data = req.body;
for (var i = 0; i < users.length; i++) {
if (id == users[i].id) {
users[i].first_name = data.first_name;
users[i].last_name = data.last_name;
res.status(200).json({
message: "User updated successfully!"
});
}
}
res.status(401).json({
message: "User not found."
});
});
Similar to our user_get
method, this function accepts a unique user ID parameter via the URL to locate our user object within the users
array. first_name
and last_name
parameters are also passed within the request body. If an ID match is made, those parameters will update for that user object and return a successful response message.
Deleting a User
And now to our final method to delete a user object:
app.delete("/user_delete/:id", function(req, res) {
var id = req.params.id;
var data = req.body;
for (var i = 0; i < users.length; i++) {
if (id == users[i].id) {
users.splice(i, 1);
res.status(200).json({
message: "User deleted successfully!"
});
}
}
res.status(401).json({
message: "User not found."
});
});
This code snippet takes the same approach as the previous methods where the users
array loops until a user ID matches. In the event of an ID match, the splice()
method is used to remove the object from the array permanently.
Conclusion
With the code and practices covered in this tutorial, you should now be able to create a simple REST API with NodeJS and the Express framework. These are only basic examples using possible real-world scenarios for user and data management. You can extend the potential of NodeJS by connecting to a database and a whole lot more.
Created: March 10, 2020