In this tutorial we are going to explain how to set up an API. We will also cover the definition of this 3-letter acronym and what it can be used for.

To follow this tutorial you will need:

A server with Ubuntu 18.04, node v13 and yarn 1.21.1 running

What is an API?

An API makes the data or functionality of an existing application available so that other applications can use it. It is what should make the notion of application programming interface clearer.

Using an API therefore allows you to use an existing program rather than re-developing it. So it’s a big time saver.

What does an API concretely do?

The first thing an API does is that it exposes, in other words, it makes functionality or data available. Most APIs require one or more API keys to work. This key allows the API to identify you as a user with the necessary rights to use the API. Finally, this authentication question is crucial when it comes to API.

Next you will see how to set up an API on your server.

Step 1 - Importing dependencies and

Use the following command to import the dependencies:

const express = require("express");

Step 2 - Instance the app

Now you will have to instance the app and the route express. Use the following commands to do this:

const app = express();
const route - express.Router();

You will also have to define the port in which the application will run. You can do this with the command:

const port = 3000;

In this example we used port 3000.

Step 3 - Set up Routes

In app.use, set the first parameter as root. In the second parameter, put the express’ router and then use two other parameters. The first must be the route you wish the user to enter, while the second must be a callback with rec and res parameters.

In the callback you will return res.send with all the responses. Use the following command to do this. In our example we returned a JSON which has a message and then entered the message:

  route.get("/", (req, res) => {
    return res.send({ message: "This API is returning a JSON" });  

Step 4 - Setting Up Server to Listen to Ports

Start the server with the port parameter and then a function that prints the console that the service was started in the right port.

For this, use the command:

app.listen(port, () => {
  console.log(`Servidor rodando na porta ${port}`;
module.exports = app;


Now you have set up an API. If you have doubts, just leave a comment and we will discuss it

Read more about: DevelopmentUbuntu