Building REST APIs using NodeJS

REST is an abbreviation that stands for REpresantational State Transfer. REST relies on a cacheable, stateless, client-server communication protocol that emits data instead of pages. This data can either be XML or JSON. In my opinion, JSON would be the best choice when using NodeJS to build API’s since it’s JavaScript oriented… And the same amount of information on a JSON response is considerably smaller in terms of size than XML which ensures faster loading time.

Using Express

Middleware functions are the heart beat of NodeJS. Since it’s an open platform, NodeJS comes with some form of Store similar to Android Play Store. It’s called NPM, which manages modules built for Node by Node developers for Node developers who do repetitive tasks that can be modularized. Express helps developers quickly build servers with routing and a bunch of other stuff that would take mountains of code to achieve if you decide to write it from scratch. After initializing your node package using npm init command, fill this into your index.js or app.js file.

var express = require("express");
var app = express();
app.use("/", (req, res, next) => {
res.json({
ok: true,
data: "Hello world"
});
}):
app.listen(process.env.PORT || 3000, () => {
console.log("Server running on port 3000");
});

And there we have our REST API that responds with JSON that looks like this.

{
"ok": true,
"data": "Hello world"
}

To run your app, use the command node app.js where app.js can be replaced by the name you’ve used on your main js file.

If the app throws any errors, eg: “Cannot find express module” it simply means you haven’t installed express and it’s as simple as npm i express — save. The dash dash save ensures that express has been added to your package.json file as a dependency. This means that once you upload your app to a hosting platform like Heroku, the service can easily install all the dependencies your app needs to run.

Introducing routes

Routing is a very powerful feature that can be quickly implemented using Express. To start using routes, create a new folder in the root where you’ll dump your route files. In my case I’ll call my folder routes to be explicit. There are a few ways you can decide to arrange your routes, you can bundle up routes of the same functionality say auth.js carries the signin, signup, logout routes or have them all independent in separate files called signin.js, signup.js and logout.js.

In the routes folder, create a new js file and call it index.js, this will be your first route. In index.js add the following code to make use of express router.

var express = require("express");
var router = express.Router();
//get
router.get("/", (req, res, next) => {
res.json({
ok: true,
data: "Index get"
});
});
//post
router.post("/", (req, res, next) => {
var username = req.body.username;
var password = req.body.password;
 var user = {
username: username,
password: password
};
 res.json({
ok: true,
userInfo: user
});
});
module.exports = router;

As you can see in the code above we have created two routes, using the same url but one of them is POST and the other is GET. The POST url accepts two parameters. But then they cannot be used yet as you need to have a middle ware called body parser.

Body Parser Middleware

The body parser is a middle ware in NPM that eases the manipulation or reading of data from the request. Either using GET to extract values from params or the request body in the case of POST. So now you’ll have to get rid of your code from line 4 to line 9 which should look like this…

var express = require("express");
var bodyParser = require("body-parser");
var app = express();
//use the body parser middleware in express
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false });
//routing to index.js file in the routes folder
app.use("/", require("./routes/index");
app.listen(process.env.PORT || 3000);

To install body parser all you have to do is be at the root of your project and type in npm i — save body-parser.

The first piece enables express to accept JSON data in the request body while closely following it in the next line is the block of code that accepts url encoded data. URL encoded data is normally found in the <form></form> element.

Run.

Now, you have a fully functional REST api that’s very simple but has no database nor security layer. To minimize the size of this article I decided to exclusively dedicate two more articles to adding a database and security since those two topics can be a little expansive and may need extra space. Check around my profile for the two articles about Database and Security on APIs as I have not yet made them, but soon will. Thank you for your time, hope you learnt something valuable today.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.