How to build an REST API with SQL Database using Loopback v4

I never had the opportunity to write an API using Loopback. I always used either Java with SpringBoot or classic JavaScript with Node.js and Express as the basic framework. Loopback v4 is actually using of course JavaScript inside but the basic is to used TypeScript. It looks that I will have to learn it.

The minus in Express that if you want to make just a simple API without working on the “client” side you just have to get rid of all the stuff which is build in Express.

I decided to go to look around what else can be found together with Express and of course I found Restify which is the same idea just without client side and Hue and few others. Also I found Loopback which catch me an eye because IBM stands behind it and it have also few advantages. A more detailed comparison can be found here. I suppose that if someone else were made the compare will found to add few features that are not covered by Loopback.

I also liked a lot the flow that is implemented in Loopback v4. Take a look here

Loopback flow from loopback.io

Anyway decided to give a try. Since is just some try I decided to go for the last version which is GA since October ’18.

First step in my case was very easy, I already have the Node.js installed, and I suppose that you my readers also have it. If not you are invited here and follow the instructions to install it for your OS. I recommend to install always the latest LTS version and not the latest since stability and long term support are very important.

Next step was to install Loopback 4

npm i -g @loopback/cli

After installing next step we can create our app.

lb4 app

The wizard to create the app is just started and you have few simple questions:

Project name: getting-started
? Project description: Getting started tutorial
? Project root directory: (getting-started)
? Application class name: StarterApplication
? Select features to enable in the project:
❯◉ Enable tslint
◉ Enable prettier
◉ Enable mocha
◉ Enable loopbackBuild
◉ Enable vscode
◉ Enable repositories
◉ Enable services

As you can see for the people using vscode as primary editor is comig with the relevant configuration. This is done partial since after I opened the project in VSCode I had to run also those two commands

npm install jshint
npm install eslint

I suppose that the “idea” that those are already installed on each developer computer was in mind of who made it. Anyway the problem is that because some “experimental” features that are in VSCode, the code just created is “painted” in few places in “red” because of stuff that can be found. The reality is that the app is running perfectly so is an issue with the VSCode. I move to IntelliJ which I prefer anyway.

Next step we can run the app and see how is working, and if it’s working.

npm start

If everything is okay, and there is no reason not to be you will have in the log just two lines

Server is running at http://127.0.0.1:3000
Try http://127.0.0.1:3000/ping

You can definitely try the address you should get to a basic white page with links. One of the links is really interesting

http://127.0.0.1:3000/explorer

You will get a very nice explorer for what you have in you app. Even nicer you will be able to test your on functions that you are writing.


Now we have a working app and we just want to add a new file with some static content. All you have to do is to go to the “public” directory and add the file. Just start the server and the file will be served directly. No code have to be added at all. Nice and promising. In the file “application.ts” you can find the line

this.static('/', path.join(__dirname, '../../public'));

which is the line that makes all this possible.


Next step is to understand what we have now and what is required if we want to add our own controller with a new endpoint.

The first step is very easy. Loopback made most of the work for us. We just have to run

lb4 controller

The wizard which creates the controllers is started and here are the options

? Controller class name: hello
? What kind of controller would you like to generate? Empty Controller
create src/controllers/hello.controller.ts
update src/controllers/index.ts

Controller hello was now created in src/controllers/

Important point to take in consideration the “test” for the new just created is not created. If we want to create tests for the new endpoints we just create we have to go to directory “test/acceptance” and create the tests by ourself.


Now a little bit about the new stuff in v4. In previous version v3 we had Datasource and Model. In the new version we have Datasource, Model and Repository. For each category and for the controllers we have in our project a different directory. Keeping all the sources in order is important.

First step we create the Model. To do it we can run the wizard

lb4 model

Since we are creating a class we should use Camel Case but is not necessary.

The next step in the wizard is very interesting. We have the possibility to choose between 2 options as “base class”. Loopback give us the possibility to “extend” a Model so we can just add more properties. The two options are :

? Please select the model base class
❯ Entity (A persisted model with an ID)
Model (A business domain object)

Let’s go for the first option to create a Model from Entity. We still have to add a field which will be the “ID”. After we add any kind of fields we want. We have a lot of types and actually usage of the ORM will take care about how the fields will be created for real in the database. In the previous version there was possible to use only the already integrated ORM but in the new version this limitation doesn’t exist anymore. We can still use the default but we can also define and use our own.

If we want to have the ID to be autogenerated we have to go to the “models” directory and open the new model created and add to the field which is the “ID” one more property “generated” with value of “true”. What is also important we have to change the “required” to false. In this way the filed value will be generated automatically by the database.


The next step is to create the Datasource. This is really special because we will create it for the moment to be as a real database on PostgreSQL (my preference) but you can use anything you want of course. What is special about this Datasource is that it can also be an external API or a message que or even other stuff.

To create the Database we just have to run command

lb4 datasource

After we provide the name we have the big surprise and everything that is supported by StrongLoop including SQL databases and NoSQL databases and other stuff is in our list of options.

Selecting the PostgreSQL (or other real database) will take us to the next step when we have to provide the connection string. Here we can provide it or we can move to next steps and provide all the parameters one by one. After the files re created in the relevant directory.


Now we want to see how we can connect for real our Model to the Datasource which is a PostgreSQL in our case. For this we need to add a Repository using Loopback wizard

lb4 repository

The wizard is very simple and we just have to choose between our datasources and the models.

New files are created in “repository” directory.

Now back to the “index.js” file. Inside the file by default we have the “main” function which will run the app.

export async function main(options: ApplicationConfig = {}) {
const app = new AppTest02(options);
await app.boot();
await app.migrateSchema();
await app.start();

const url = app.restServer.url;
console.log(`Server is running at ${url}`);
console.log(`Try ${url}/ping`);

return app;
}

We can add the “await app.migrateSchema();” so every time we are running the app the database is synchronised with our models which it have some advantages but also it increase the loading time and also it can create some risks. A much more safer method is to run command

npm run migrate

This command will run only the migration process which is described in file “migrate.ts”. This is much more safer approach and also we can customise specific things if we need.

Now if we will take a look in our database we will see that we have the new table created.


Next step is to connect the database and our model to the CRUD functions. To do this we need to use a new wizard which is the controller one.

lb4 controller

First we give a name, for the second option we select “REST Controller with CRUD functions” option. We continue by selecting our Model and repository. We will select the type of the filed which is the “ID” (the field we already created) and after we can customise the endpoint (http path). New files are created in “controllers” directory.

Now we just have to run the app and we are done.

npm start

We have now in the API explorer all the functions including what we need for all the basic operations.

I will be happy to get your feedbacks.

Thanks