Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 10, 2021 07:58 pm GMT

How to Build RESTful API using Node.js

What is REST API?

Nowadays, the word API becomes more and more popular since we are living in the digital era of the Internet. Even if you are not a coder, probably you have heard the word API at least a few times. More importantly, if you are a coder APIs are all around code in many different forms, therefore it's good to know something about them. Indeed there are many different types of APIs, and the word API stands for application programming interface, while REST means representational state transfer, and this type of API will be the main focus of this article. Don't worry if those words do not mean too much to you at this point. So what are APIs and what do we need them for? Think of APIs as microprograms or microservices that help us with various different tasks and connect various pieces of functionalities in the applications. Sometimes they may be served on the external server, and work as a separate program. REST API is the best example in this case, as it is generally hosted on a separate server and serve our app on the frontend side. For instance, let's say that we have an application that manages doctors appointments, we can create the whole visual part of the app with condition rendering on the front part, but what about database all of the logic related to communicating with the database, registering users, authenticating them, and so on? In this case, we will need REST API which will take care of all of the logic related to storing data, accessing given routes and all of the other security stuff. It will be also our bridge between the database and our app, let's say that the API itself will be between the visual part of the app, and the database itself. Before we move on to building the REST API itself, there is one more question. How does the frontend app communicate with the backend (in this case REST API)? Just like we humans have different languages, English is a kind of a "lingua franca" which means an international language for communication all around the world, very similar thing happens in this world of web apps as well. However, in this case, we have:

I will not go over the details, but I definitely recommend you to go over the definitions on MDN. To sum up, we can say that we can communicate with REST API via API Endpoints which are just links with specific endings, therefore word "endpoint", we also have to specify request method and as a result, we can get some data with response code from the server. We can also add some extra details such as cookies, or authorization details in headers or longer information in form of messages in the body part of the request. Moreover, since these ways of communication are always more or less the same, we do not need to care what languages were used on what side of the application. That is how we have for example frontend apps are written in JavaScript, while backend servers run very often on different languages such as C#, PHP or Java. However, since the invention of Node.js, we can now also use JavaScript on the backend side, even though it doesn't make any difference for our application on the frontend.

Node.js and Express

After the short theoretical introduction to what are APIs and how do web applications work, now it's time to move on to the details. In this article we will use the only JavaScript to build REST API, therefore it's good to know few things about it beforehand. Node.js is a program written in C++ that is able to run the V8 engine of JS (the same that runs inside of Google Chrome web browser), and thanks to this invention we can run JavaScript applications outside of the browser. In other words, we had to run the JS scripts attached to the HTML files which were parsed by browsers and then executed. However, thanks to Node.js, it is possible to write JavaScript pretty much anywhere, and run it with the help of Node.js. There are of course few differences between the browser environment and Node.js environment, such as we do not have DOM outside of the browser, but from the other side we can get access to the local files, and do other more complex operations just like with any other programming languages.

Express

It is very easy to guess that thanks to the power of Node.js we can do a lot of things with JavaScript, but things can grow very complex and get out of hand very quickly. Just like on the frontend side, almost nobody is using vanilla JavaScript anymore, for the sake of Not Repeating Ourselves, the same thing applies to Node.js and backend practices. When on the frontend we use a lot of tools, frameworks, and libraries such as React, Vue, or Angular, also here there are similar tools. One of the most popular frameworks in terms of Node.js is Express. In fact, it is kind of a small library that helps us write less verbose code and makes things even easier. It's not opinionated and you can use it just like an additional library. In this article, we will use both Node.js with Express framework to make the code as much readable as possible.

Hello API World

Let's finally move on to the code part, we will create a super simple application with just a few lines of code. Before we start coding our application, we will need few things to make it work:

First of all, download and install Node.js (there may be some differences depending on what OS you use). There are many versions of Node.js but anything over 12 should be OK with this tutorials since there are some parts that may not work with older Node.js versions. Once you have Node.js installed on your computer, you can check if everything is OK by going to the terminal and typing node -v, if you can see information about Node.js, then everything should be ready.

The next step is to create a folder and initiate a configuration file called (package.json). If you use Linux or macOS, then you can follow these commands:

  1. mkdir restapi
  2. cd restapi
  3. npm init -y
  4. touch app.js

The commands may differ depending on the system, but the idea is to create a new folder called "restapi", open that folder and initiate an entry file to our project called "package.json" with the flag -y which simply means answering "yes" to all of the questions. If you skip this flag, then you will have to answer them manually. In the last part, we create file app.js where our API's code will live.

After creating the folder, and necessary files you can open the code editor and go to the given folder. The first modification will be to add one line to the package.json file, which will let us use ES6 way of importing modules instead of "commonjs" style such as const express = require("express"); we will be able to use import express from "express";. To enable this option, open package.json file and under "description" add the following line "type": "module",. Additionally, you can also add the following line "start": "node app" inside of the "scripts" block. This will let you use npm start command just like you have probably used before with React, for example, otherwise, we would have to type node app each time in the terminal to execute our app.js file with Node.js. There is one more detail - Express. Go to the terminal, make sure that your terminal is open inside of the project folder and type in the following command npm i express - this command means use the npm package manager, and i install the package called express. Before we had to write install instead of i and also add the flag --save to add the module to the package.json file.

Now open app.js file inside of your code editor, and build our API:

  1. We will need an express framework that why we have to import it firstly with import express from "express";

  2. Then we initiate express inside of variable called app
    const app = express();

  3. Our application, for the time being, will check only one route "/", and only one method "GET".

app.get("/", (req, res) => {  res.send("hello world");});

First of all inside of the app object, we have method .get which takes 2 parameters

  • "/" string which is the route on which will it listen,
  • (req, res) callback function with two parameters req - request and res - result. Since we do not care much about the request at this point, just hitting the endpoint with the "GET" method, we will only send something back. In this case, we send back string "hello world" back to the sender.
  1. It's time to start our server and set it to listen on a given port.

app.listen(5000);

Method listens, starts our server, and its first parameter is the value of the port that our app will listen on - in this case, 5000, but feel free to change it to the other values.

The overall code should look like that:

import express from "express";const app = express();app.get("/", (req, res) => {  res.send("hello world");});app.listen(5000);

Now you can type in npm start or node app in the terminal, open your web browser and go to the http://localhost:5000. On that address "hello world" text should be visible.

You can also do the same with Postman, by sending GET request to that address

To terminate the server, you can hit CTRL + C

That's all! Congratulations! :) Our first very simple REST API is ready. But in real life, of course, it is not enough there are many other things to learn and improve.

Refactoring

For this tutorial, it is almost finished, but before finishing let's refactor our code a little bit more and introduce some very simple design patterns.

Middleware

What is it? Middleware, like the name, can suggest is some kind of software or let's call it methods that run in the middle of our requests and responses. There are many middlewares that you may want to end up adding to your app, but for now, we will need some absolute basics.

Right after const app = express(); you can add following code:

app.use(express.json());app.use(express.urlencoded());

Method .use is generally used to add middlewares for the connections made with the express, in this case, we have .json() and .urlencoded. These two middlewares will parse JSON files and request inputs to readable strings and numbers.

process.env

Since the backend side is always much more vulnerable to hacker attacks, as it may store very sensitive information such as passwords to the databases etc. It's better to take some precautions and never share those kinds of values in the public repositories. That is why we use environmental config files, such as .env. Let's store our port value inside of such an environmental file.

First of all, we will need to download the npm package for this purpose npm i dotenv' then import it withimport dotenv from "dotenv";and set it up with the following linedotenv.config();. Now you can create a new file called.envinside of the same folder. Inside of the.envfile add the following linePORT=5000. Then going back to theapp.jsfile, create a variable called port and assign it to the value from the.envfile like thatconst port = process.env.PORT;Now you can modify the last line of the code toapp.listen(port);`. This will enable us to change port values dynamically, depending on the given server. You can also add a callback as a second parameter.


app.listen(port, () => {
console.log(
Listening on port: ${port}`);
});

`

Express Router

REST API can grow very big and complex, so it is better to keep the routes outside of the main file. Let's create a separate folder for the given routes, and add a file called "mainRouter.js". Inside of this file, we will use again Express, but this time it's the Router method that helps to reroute different paths easily.

`
import express from "express";
import MainController from "../controllers/MainController.js";
const mainRouter = express.Router();

const mainController = new MainController();

mainRouter.get("/", mainController.HelloWorld);

export default mainRouter;

`

Controller

Most of the code should be clear by now, but you may be wondering what is "MainController"? The more routes we have in our app, the more logic to handle each route we have, so let's go a bit deeper and divide this part as well. In the main folder, create a folder called "controllers" and there create a new file called "MainController.js". Inside of this file, we create a class with a public method.

`
class MainController {
HelloWorld(req, res) {
return res.send("Hello World");
}
}

export default MainController;
`

Almost there! Now we can also edit "app.js" file so everything should look like that:

`
import express from "express";
import dotenv from "dotenv";
import mainRouter from "./routes/mainRouter.js";

dotenv.config();

const app = express();

const port = process.env.PORT;

app.use(express.json());
app.use(express.urlencoded());

app.use("/", mainRouter);

app.listen(port, () => {
console.log(Listening on port: ${port});
});
`

You can try to run it once again, everything should work just like before.

Conclusion

Congratulations if you made it that far! However, it is just a beginning and there are many more things to learn about Node.js and Express. The application is super simple, but hopefully, it gave you the initial idea of how to create REST APIs in Node.js. Stay tuned for more, as in my upcoming articles, we will add new features to this API.


Original Link: https://dev.to/pawel/how-to-build-restful-api-using-node-js-3dpp

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To