TL;DR: In this tutorial, I'll show you how to leverage Loopback to build out your REST APIs quickly. Check out the repo to get the code.

RESTful API Overview

API (Application Programming Interface) endpoints are the connections between your application and the rest of the developer community. You can decide to open up your data source to the world by crafting API endpoints that developers can consume. Furthermore, developing an application that will require clients for different platforms such as Desktop, Android, iOS and Windows platform will most likely need a RESTful API for all the clients to access data seamlessly. Unless of course you are engaging GraphQL, the alternate option to RESTful APIs.

If you have built a RESTful API from scratch before now, you'll understand that there are a lot of processes you have to follow, a lot of code to write, and a lot of testing to do to ensure your APIs work correctly. Loopback was designed to fast-track those processes and take away the pain of developing RESTful APIs from scratch.

What is Loopback

Loopback is a highly extensible open-source Node.js framework that can be used to build dynamic end-to-end REST APIs. With little or no code, Loopback hands you the power to:

Loopback runs on-premises or in the cloud. It also provides several add-on components for file management, 3rd-party login, OAuth2, Storage providers e.t.c. Simply put, Loopback allows you to create REST APIs in minutes. It does that by:

Providing a CLI tool for use.

Providing a built-in API explorer.

Allowing a developer create models based on a particular schema.

Allowing a developer to create dynamic models in the absence of a schema.

Application Overview

In this tutorial, we'll build a RESTful API for Star Wars. A Star Wars API, SWAPI already exists. Rather than crafting an entirely different API, we'll build a clone of the Star Wars API. The objective of building the API clone is to learn how to craft APIs quickly with Loopback. Consider a case where you are assigned the task of designing an API for a new interesting HBO show, e.g Game of Thrones, that has caught the attention of Google & Facebook.

Explore SWAPI (Star Wars API) Design

We will explore the API endpoints for SWAPI(Star Wars API). There are six endpoints for the Star Wars API:

Planets - /planets

People - /people

Starships - /starships

Species - /species

Vehicles - /vehicles

Films - /films

Planets - This resource is about the planetary bodies in the Star Wars Universe.

GET - /planets returns a list of all the planets.

GET - /planets/<id> returns the details of a specific planet.

People - This resource deals with characters in the Star Wars Universe.

GET - /people returns a list of all the characters.

GET - /planets/<id> returns the details of a specific character.

Starships - This resource is about the transport crafts that have hyperdrive capability in the Star Wars Universe.

GET - /starships returns a list of all the starships.

GET - /starships/<id> returns the details of a specific starship.

Vehicles - This resource is about the transport crafts that do not have hyperdrive capability.

GET - /vehicles returns a list of all the vehicles.

GET - /vehicles/<id> returns the details of vehicle.

Species - This resource is about the type of characters in the Star Wars Universe.

GET - /species returns a list of all the species.

GET - /species/<id> returns the details of a specific specie.

Films - This resource is about the episodes of the Star Wars film.

GET - /films returns a list of all the episodes.

GET - /films/<id> returns the details of a specific film.

In the analysis above, you'll observe that all the calls for the endpoints are GET requests. We'll ensure that the other HTTP verbs, POST, PUT, and DELETE will be active for these endpoints when building the API.

Getting Started: Building Star Wars API

Let's get started. Go ahead and install Loopback:

npm install -g loopback-cli

Once you are done installing, go ahead and run the loopback command:

lb

The Loopback CLI is an interactive wizard. A series of questions will be asked such as the name of the application, directory to store the project, the version of loopback you prefer and the kind of application you want loopback to provision. Answer the questions:

Next, move into the starwars directory from the terminal.

Create Models

We'll create all the models needed for this API. As mentioned earlier, we have 6 resources, People, Films, Starships, Species, Vehicles and Planets. In our API, we'll deal with just 5.

lb model

It will prompt you for a model name: Enter People. Next, select db(memory) as the data source. Go ahead and select PersistedModel as the model's base class. Hit Enter to expose People via the REST API.

Next, select common model. Selecting this ensures that the models are stored in the common directory. You can also decide to store them in the server directory only. The server directory is used to store server-side models while the common directory stores models that can potentially used by both server and client Loopback APIs.

Now, you are going to define properties for the People model. The properties are:

Property name: name, Property type: string, Required? Yes

Property name: height, Property type: number, Required? Yes

Property name: mass, Property type: number, Required? Yes

Property name: gender, Property type: string, Required? Yes

Repeat the same process for the Films, Starships, Species and Planets models with these properties:

Note: You'll have to run lb model on your terminal everytime you need to create a new model.

Film

Property name: title, Property type: string, Required? Yes

Property name: opening_crawl, Property type: string, Required? Yes

Property name: director, Property type: string, Required? Yes

Property name: producer, Property type: string, Required? Yes

Starship

Property name: name, Property type: string, Required? Yes

Property name: model, Property type: string, Required? Yes

Property name: manufacturer, Property type: string, Required? Yes

Property name: passengers, Property type: number, Required? Yes

Property name: class, Property type: string, Required? Yes

Specie

Property name: name, Property type: string, Required? Yes

Property name: classification, Property type: string, Required? Yes

Property name: designation, Property type: string, Required? Yes

Property name: average_height, Property type: number, Required? Yes

Property name: skin_color, Property type: string, Required? Yes

Property name: language, Property type: string, Required? Yes

Planet

Property name: name, Property type: string, Required? Yes

Property name: rotation_period, Property type: number, Required? Yes

Property name: orbital_period, Property type: number, Required? Yes

Property name: diameter, Property type: number, Required? Yes

Property name: population, Property type: nunber, Required? Yes

Once you are done provisioning all the models, head over to the common/models directory. In this directory, you'll see all the models in .js and .json files. For example, people.js and people.json file.

Next, test the API. Run the command below in the root path of the project:

node .

Check out your API explorer.

Here, you can see the structure of the Species resource. Clicking the Try it out button hits the /api/species endpoint and returns a result. Right now, there is no data so it returns an empty array.

Note: The API explorer allows you test the REST API operations during development.

Let's make a POST request to the /api/film endpoint using the explorer. Head over to http://localhost:3000/explorer/#!/Films/Films_create.

In the diagram above, I highlighted three steps:

Click on the text-area box that contains the parameter type. Once clicked, it immediately appears in box 2.

Edit the JSON in the box.

Click the Try it out button to execute the POST operation

Note: If you are making a POST request to create a new record, remove the id attribute and value from the JSON in the box. id is automatically assigned.

Result of POST operation

Now check out the URL, http://localhost:3000/api/films.

Try making a POST request to the films endpoint with Postman.

Voila! Be careful, our API is not connected to any data source yet.

Next, let's connect our API to a data source.

Connect API to Data Source

Let's connect our API to a database. Luckily for us, loopback supports a lot of data sources. Head over to your terminal and run the following command:

lb datasource

It will prompt you for a name. Enter mysqlDs.

mysqlDs is MySQL Datasource for short. Yes, we'll make use of MySQL. So, make sure you have MySQL database installed on your machine.

Next, select MySQLas the connector for mysqlDs and hit Enter. Go ahead and supply the host, port, user and password values for the connection string. And enter Yes to install the loopback-connector-mysql tool.

The connection details can be found at server/datasources.json. Feel free to edit the file anytime.

Connect API to MySQL

Open up server/model-config.json and change the value of the dataSource property from db to mysqlDs for each of the models.

The bunch of code above simply creates the tables and seeds them with the data provided. Whenever your app is initialized, the script will run and ensure the tables exist and are seeded with the right data.

Head over to your console and start your app again:

node .

Create Tables and seed data

Check your database. The new tables and data should reflect there.

Test the API

Now that our API is connected to MySQL. Let's test our API for persistence. Make a GET request to http://localhost:3000/api/planets.

Initial GET Request

Go ahead and make a POST request to the URL.

POST Request

Now, make another GET request to the URL

Another GET Request

Yes, we see three records. Our data was persisted successfully. You can test out the PUT, PATCH, and DELETE operations for the Planets and other API endpoints.

Secure the Star Wars API

The majority of the APIs we use on a daily basis have a means of authorizing users to make changes to them. We'll go ahead and secure some of these API endpoints with JSON Web Tokens.

JSON Web Tokens, commonly known as JWTs, are tokens that are used to authenticate users on applications. This technology has gained popularity over the past few years because it enables backends to accept requests simply by validating the contents of these JWTs. That is, applications that use JWTs no longer have to hold cookies or other session data about their users. This characteristic facilitates scalability while keeping applications secure.

Whenever the user wants to access a protected route or resource (an endpoint), the user agent must send the JWT, usually in the Authorization header using the Bearer schema, along with the request.

When the API receives a request with a JWT, the first thing it does is to validate the token. This consists of a series of steps, and if any of these fails then, the request must be rejected. The following list shows the validation steps needed:

For starters, if you haven't done so yet, this is a good time to sign up for a free Auth0 account. Having an Auth0 account, the first thing that we must do is to create a new API on the dashboard. An API is an entity that represents an external resource, capable of accepting and responding to protected resource requests made by clients. And we are dealing with an API here, SWAPI (Star Wars API).

Click on the APIs menu item and then the Create API button. You will need to give your API a name and an identifier. The name can be anything you choose, so make it as descriptive as you want. The identifier will be used to identify your API, this field cannot be changed once set. For our example, I'll name the API, Star Wars API, and for the identifier I'll set it as https://starwarsapi.com. We'll leave the signing algorithm as RS256 and click on the Create API button.

Create a New API

Creating the Star Wars API

You can define scopes in this section

Head over to your terminal and install the following node modules:

npm install express-jwt jwks-rsa --save

Open up your server/server.js file and modify the code to look like this:

Conclusion

Loopback is a great Node.js framework that can be used to design and build your APIs quickly as shown in this tutorial. It is a project backed up by IBM and the Strongloop team. They are committed to maintaining and improving on this amazing open source project.