Building a REST API with Node.JS

tech

Hey guys, today we’re going to start a tutorial about REST API with Node.JS.

In this first part, we’ll learn how to configure our API and organize the routes.

Let’s go!

What is a REST API?

For start we must understand what is a REST API, right?

Ok so, REST API is an interface that provides data in a standardized format based on HTTP requests.

REST uses the verbs (GET, POST, DELETE, UPDATE) of the HTTP protocol as the basis for requests.

For example, we can have equal end-points that do different things, according to the requisition method (verb).

The URL https://exemplo.com.br/usuario/57, if requested by a GET, will bring the information pertaining to the user with ID 57, if requested by a DELETE it will exclude the user with ID 57 from the database, and if done with UPDATE it changes user data of user ID 57.

That why it is important to pay attention to the requisition methods.

Let’s see this in practice?

Let’s start writing our API, for that it is necessary to have Node.JS and NPM installed:

Installing on Linux

Installing on Mac and Windows

After that, let’s open our terminal and create a folder for our project, and walk to it:

mkdir api-rest
cd api-rest

//Installing NPM
npm init -y

We will use two packages to start: Express and Cors.

“Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.”

The cors will allow your API to receive requests from cross domains.

We can also configure to receive only from specific domains (if necessary) for greater API security. Learn more about CORS here.

So let’s install them:

npm i express cors

Configuration

We can create a file in the root, called server.js, where we will configure express.

const express = require('express');
const cors = require('cors');
const app = express();
 
app.use(cors());
app.use(express.json());
app.listen(3333);

With the code above, we configured our API to accept requests from any source with cors and to return everything in JSON.

That done we already have our API, we can start it using nodemon.

Nodemon is a helper that will be monitoring the files of our API, as soon as we save a change it will restart the server, so we don’t have to do it manually.

Let’s install the nodemon globally, to make it easier.

npm i -g nodemon

Running the API

nodemon server.js

Controllers

A controller is responsible for controlling the way a user interacts with an MVC application and has the flow of logical control for the application. It is the controller that determines which response will be sent back to the user when he makes a request.

Creating a Controller:

We created a folder inside src called Controllers, and inside it, a file called UserController.js with the following code:

exports.post = (req, res, next) => {
   res.status(201).send('Rota POST!');
};
 
exports.put = (req, res, next) => {
   let id = req.params.id;
   res.status(201).send(`Rota PUT com ID! --> ${id}`);
};
 
exports.delete = (req, res, next) => {
   let id = req.params.id;
   res.status(200).send(`Rota DELETE com ID! --> ${id}`);
};
 
exports.get = (req, res, next) => {
   res.status(200).send('Rota GET!');
};
 
exports.getById = (req, res, next) => {
   let id = req.params.id;
   res.status(200).send(`Rota GET com ID! ${id}`);
};

What we are doing there is creating the standard methods for each type of verb, HTTP.

These methods are very common in real applications (however they are renamed for the exact function, but for teaching purposes, it will be like this today), the famous CRUD.

C — Create (POST)

R — Read (GET)

U — Update (PUT)

D — Delete (DELETE)

We are also setting the status of the request (200, 201), which means success, and success without returning an object, respectively. Learn more about Status Request.

That done, we will create our routes, so we can access the controllers.

Within src, we create a Routes folder;

Within routes, we will create an index.js file (where we will join all the routes) and another UserRoute.js where we will have the routes for the user.

index.js:

const UserRoute = require('./UserRoute');

module.exports = (app) => {
   UserRoute(app)
}

UserRoute.js:

const UserController = require('../Controllers/UserController');

module.exports = (app) => {
   app.post('/usuario', UserController.post);
   app.put('/usuario/:id', UserController.put);
   app.delete('/usuario/:id', UserController.delete);
   app.get('/usuarios', UserController.get);
   app.get('/usuario/:id', UserController.getById);
}

Now every time we create a route file, just import it into the Routes index file, as we did with the user.

And now we need to make a small change to server.js, for the routes work.

const express = require('express');
const cors = require('cors');
const app = express();

require('./src/Routes/index')(app); // <--- just add this line

app.use(cors());
app.use(express.json());
app.listen(3333);

That done! Now we can test if your nodemon is not running just type on terminal: nodemon server.js.


That’s all , folks!

In this article we saw the basics to have our API working simply and effectively.

And in the next steps, we will connect with mongodb, put JWT authentication, error handling and some other things, so stay tuned!