Building an API With Node.js
With the Node.js environment installed and ready to run, we will explore the
creation of our REST API application. This type of application is currently being developed by numerous projects and companies, as it provides the benefit of creating an application that focuses solely on
on the data feed of any client-side application.
Nowadays, it is quite common to create web applications and or mobile applications that consume data from one or more APIs.
This makes several the types of client applications consult the same server focused on data processing. In addition, it also allows that each application — client or server — is worked on by different teams. We will first build an API, but throughout the last chapters we will build a simple client-side web application to consume data from our API.
To start developing the API, we
is going to use a very popular web frame called Express.
Introduction to Express
Express is a minimalist web framework that was highly inspired in Sinatra framework from Ruby language. With this module, you can create from small applications to large and complex ones. This framework allows you to build APIs and also to create simple web sites.
It’s focused to work with views , routes and controllers , only models is not handled by this framework, giving you the freedom to use any persistence framework without creating any incompatibility or conflict in the application.
This is a big advantage, because there’re a lot of ODM
(Object Data Mapper) and also ORM (Object Relational Mapping) available. You can use anyone with Express without problem, you just need to load this kind of module, write some models and
use them inside the controllers , routes or views .
To sum up, you can see a list of Express main features bellow:
• Robust routing;
• Easily integratable with a lot of template engines;
• Minimalist code;
• Works with middlewares concept;
• A huge list of 3rd-party middlewares to integrate;
• Content negotiation;
• Adopt standards and best practices of REST APIs;
Initiation of the pilot project
What about creating a project in practice? From this first part, we will explore a few on how to create a REST API using some Node.js frames.
Our application will be a simple task manager, it will be divided into two projects: API and Web application. Our API will be called Build_Api_Node_part1 and will have the following characteristics :
- List of tasks;
- Create, delete and update a task;
- Create, delete and update a user data;
- User authentication;
- API documentation page;
Pilot project source code
If you are curious to check out the source code of all projects that are going to be explored in this book, just access this link: https://github.com/Savalone47/Build_Api_Node_part1
To begin, we will create our first project called Api_Node , using these commands:
mkdir Api_Node
cd Api_Node
npm init -y
The currenty Node.js version does not support ES6 perfectly, but we can use a module that emulates some of the resources from ES6/ES7 to make our codes cooler. To do this, we are going to install the babel . It’s JavaScript transpiler responsible to convert a ES6/ES7 codes to a ES5 code only when the JavaScript runtime doesn’t recognize some ES6/ES7 features.
To use all features from ES6/ES7, we are going to install babel-cli and babel-preset-es2015 modules in the project, running this command:
npm install babel-cli@6.5.1 babel-preset-es2015@6.5.0 — save
npm install express@4.17.1 — save
npm install consign@0.1.6 — save
Now you need to link the preset babel-preset-es2015 to be recognized by the babel-cli , to do this, just create the file .babelrc with this simple code:
Installing Express, we’ll create our first code. This code is going to load the express module, create a simple endpoint using the GET / via function app.get(“/”) and start the server in the port 3000
using the function app.listen() . To do this, create the app.js file using this code:
Then, open your browser and go to: localhost:3000
If nothing goes wrong, a JSON content will be displayed, similar to the image bellow:
Apply a simple and static resource
REST APIs works with the concept of creates and manipulates resources. These resources are entities that are used for queries, entries, updating and deleting data, by the way, everything is based on manipulating data from resources.
An API aims to address and unify the data to, in the end, build and show a resource. Initially, we are going to work with static data, but throughout the book we will make some refactorings to integrate a database.
During this time, static data will only be used to mould an end point. To mold our API, we will include a route via the app.get(“/node”) function, which will return only a static JSON via the res.json() function, which is responsible for rendering json content as output. Here we anticipate the execution of our app.js file, here is how the result will look like :
Module loading arrangement
Indeed, write all endpoints into index.js won’t be a smart move, especially if your application has a lot of them. So, let’s arrange the directories and the loading of all codes according to their responsibilities.
We are going to apply the MVR (Model-View-Router) pattern to arrange this things. To do it, we’ll use the consign module, which allows to load and inject dependencies easily. So, let’s install!
With this new module installed, let’s migrate the endpoints from index.js file creating one new files into the new directory named routes . To do this, create the file routes/task.js :
Move the endpoint function app.get(“/node”) from app.js to his new file routes/task.js :
To finish this step, edit the app.js to be able to load those routes via consign module and start the server:
That’s it, we have just arranged the loading of all routes. Note that, at this point we are only focusing on working with VR (view and router) from MVR pattern. In our case, the JSON outputs are
considered as views which are provided by the routes. The next step will be arranging the models. Let’s create the models directory and, back to app.js add one more include() function inside the consign() to allow the loading of the models before the routes . To make this modification clearer,
edit the app.js :
In this moment, the consign() function won’t load any model, because the directory models doesn’t exists. To fill this gap, let’s temporarily create a model with static data, just to finish this step. To do
this, create the file models/task.js and filling with these codes:
To call it in the routes/task.js file, you are going to load this module via app variable. After all, the modules added by consign() function are injected into a main variable, in our case, injected into app via consign().into(app); . To see how to use a loaded module, in this case, we’ll use the
app.models.task module, edit the routes/task.js following this code:
To finish these refactorings, let’s create a file, which is going to load all the middlewares and specific settings of Express. Currently, we only have a simple configuration about JSON’s format, which occurs via function app.set(“json spaces”, 4) . But, we are going to include another settings, in
this case, it will be the server port calling the app.set(“port”, 3000) function.