Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Create A Simple RESTful API With Node.js

TwitterFacebookRedditLinkedInHacker News

I’ve written a few tutorials regarding Node.js and the Express.js framework, but I never took a step back and explained how to make a super simple RESTful API for processing HTTP requests from a front-facing interface.

With this API created, you can use it with just about any application that can submit HTTP requests. It is a great way to test a mobile application or one that uses JavaScript frameworks like jQuery, ReactJS, or AngularJS.

There are a few requirements prior to following this tutorial:

  • You must have Node.js installed on your computer.
  • The Node Package Manager (NPM) must be up to date.

With that noted, go ahead and create a new directory for the project to live. I’m using a Mac and will be doing everything in a directory on the Desktop. Don’t be alarmed by my use of the Terminal. Create the directory like so:

mkdir ~/Desktop/SimpleAPI

Navigate into the new directory and initiate a new NPM project:

cd ~/Desktop/SimpleAPI
npm init

You’ll be asked a series of questions. Answer them appropriately or just paste the following in the package.json file it creates at the end:

{
    "name": "nodejs-api-sample",
    "version": "1.0.0",
    "description": "An example of making a Node.js API server",
    "author": "Nic Raboy",
    "license": "MIT"
}

The project is now ready.

We’re going to use Express as our Node.js framework so this requires us to install two packages with NPM:

npm install express --save
npm install body-parser --save

The body-parser package allows our API to process POST requests.

Before going any further, let’s take a look at our project structure:

SimpleAPI
    package.json
    app.js
    routes
        routes.js

We’ve already taken care of package.json so let’s move onto the app.js file. It is a wrapper for all server configuration and included files. For example we’ll determine what port to use and what routes to include in this file. Create it and include the following code:

var express = require("express");
var bodyParser = require("body-parser");
var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

var routes = require("./routes/routes.js")(app);

var server = app.listen(3000, function () {
    console.log("Listening on port %s...", server.address().port);
});

To explain what we just did, we are first including the two packages and configuring the body parser to accept JSON as well as url encoded values.

When the server starts, it will listen for requests on port 3000.

This leaves us with the following line:

var routes = require("./routes/routes.js")(app);

All API endpoints will appear in this file. So let’s go ahead and open routes/routes.js found in the project root and add the skeleton code for this file:

var appRouter = function(app) {

}

module.exports = appRouter;

We are passing the app variable from app.js and then exporting the appRouter variable to be used by whatever calls it in our project. This means anything found in that function will be usable.

So what might an example route look like? Add the following into the appRouter function:

app.get("/", function(req, res) {
    res.send("Hello World");
});

Alright that route isn’t the most exiting, but here is what it is doing. When the root of the application is requested via a GET request, the text Hello World will be returned. By root of the application I mean http://localhost:3000.

So how about creating some routes that are actually useful? Let’s say we want to have a route for creating accounts and a route for getting account information. Starting with getting particular accounts, look at the following:

app.get("/account", function(req, res) {
    var accountMock = {
        "username": "nraboy",
        "password": "1234",
        "twitter": "@nraboy"
    }
    if(!req.query.username) {
        return res.send({"status": "error", "message": "missing username"});
    } else if(req.query.username != accountMock.username) {
        return res.send({"status": "error", "message": "wrong username"});
    } else {
        return res.send(accountMock);
    }
});

Yes I put the password in plain text for my mock data. Of course you shouldn’t do this in production. Beyond that, what we’re doing is we’re accepting GET requests on the /account endpoint. The request must contain a username query parameter. If the username doesn’t exist or doesn’t match the one in our mock data we return an error. Otherwise we return the mock data object.

In production you’ll probably want to go against a database rather than using mock data.

Now let’s look at an endpoint in our API for creating accounts.

app.post("/account", function(req, res) {
    if(!req.body.username || !req.body.password || !req.body.twitter) {
        return res.send({"status": "error", "message": "missing a parameter"});
    } else {
        return res.send(req.body);
    }
});

You’ll notice I chose to use the same endpoint. Instead of a GET request, this endpoint is only accessed over a POST request. As long as the required body parameters exist in the request, we are just choosing to return them. Again in production you’ll probably want to include some database logic.

We have a Node.js application with three API endpoints now. Let’s go ahead and test it out.

Since we are requiring two packages (Express and Body Parser), we need to install the for the first time. With the project as your current working directory in the Terminal or Command Prompt, run the following:

npm install

Now you can go ahead and run the application:

node app.js

Try hitting one of the GET endpoints from your browser with the host as http://localhost:3000. You should get a response. You’ll need a browser extension or something else in order to test the POST endpoint.

Conclusion

We didn’t use a database in this example, but you saw how to make a very simple RESTful API using Node.js and the Express.js framework. I personally whip something like this up when I need to test my Ionic Framework and React Native applications. Even without real data it is still good for testing your front-end applications.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.