No REST for the Wicked: Configuring a REST Data Source with Loopback 4

One of the most important tools available to software developers today is the ability to utilize web services in their applications. Put simply, a web service is a program that has been developed to perform a specific function and has been made available to developers in the form of an API (Application Programming Interface), whether for free, or as a product. Some examples of web services are Google’s Geolocation service, the Omdbapi movie database and math.js, to name a few. They each perform one or more tasks well, which is what web services try to accomplish. Web services help developers abide by the software development methodology of having a separation of concerns. In other words, a program should be specific. It should perform one or more tasks well. Often times, developers suffer from trying to do too much in a single application, and end up with difficult-to-read spaghetti code. Developers might choose to build their own web services, or to utilize those that have already been developed. For example, a developer might be tasked with creating an online web app for users to find branches of a bank that is nearest to their current location. Rather than reinvent the wheel, which is something that ought to be avoided, they could instead make use of Google’s Geolocation service to determine the nearest bank branch and provide directions to the user. In doing so, the developer has drastically reduced the time to market for the app. This is efficient programming.

In this tutorial, we will be connecting a Loopback 4 application to the omdbapi movie database. Open the terminal, and let’s get started.

First, create a new LB4 application:

lb4 app <app_name>

Now, add a datasource, connecting the application to the omdbapi web service:

lb4 datasource

Provide a name for the datasource (something meaningful).

Since the omdbapi web service is a REST (Representational State Transfer) service, select the REST connector, as seen below:

Image for post
Image for post

Set the base URL to “http://www.omdbapi.com/”.

There is no need to enter anything else. Simply press ENTER until the datasource has been successfully added.

There should now be a “datasources” sub-folder in your “src” folder, containing a “.ts” class file and “.json” configuration for your newly-added datasource. In order to fully-configure the datasource, the “.json” file will need to be modified.

Within the datasource.json file, add the following configuration after the “baseURL” property:

"options": {"headers": {"content-type": "application/json"}},"operations": [{"template": {"method": "GET","url": "http://www.omdbapi.com/?apikey={apiKey}&t={title}"},"functions": {"getDetails": ["apiKey", "title"]}}]

Now, save the file and let’s breakdown the above configuration.

While not necessary, we added an “options” property, which specifies the content-type. More importantly, we added an “operations” property, which contains an array of the operations exposed by the web service that we plan to utilize in our application. This property has a single object which provides a template for the operation, along with a named function property. In this case, we are specifying the getDetails function, which is an arbitrary name for the web service function exposed at the url: http://www.omdbapi.com/?apikey={apiKey}&t={title}. We say that this function will accept an array of strings containing an apiKey and a title (for the movie or show). In the template, we specify the method, or type of HTTP request being performed at the url (in this case, a GET request). We also specify the url related to this function. Since the apiKey and title vary depending on the request, we use string interpolation to obtain those values from arguments sent to the getDetails function. All we do here is give that long url a name (getDetails), so that we can treat it as a function in our application. Your .json file should look like this:

Image for post
Image for post

At this point, we are 50% complete. Now that we have a datasource, we need to create a service, which utilizes the datasource configuration to connect to the web service and make requests.

Create a new service and select the newly-configured datasource:

lb4 service

After lb4 works its magic, you should see a services folder with the new service. Open this file, as we’ll modify it slightly.

Add the following code to the exported-interface for your service:

// tslint: disable-next-line:no-anygetDetails(apiKey: string, title: string): Promise<any>;

This will define the getDetails function, which we previously added to our datasource. Your service should look something like this:

Image for post
Image for post

We’re so close to being finished. The last thing we need in order to call the web service, and actually test our datasource, is a controller.

Add an empty controller:

lb4 controller

Add the following imports to the controller class:

import {inject} from '@loopback/context';import {get, param} from '@loopback/rest';import {OmdapiService} from '../services';

Within the controller’s constructor, inject the imported service:

constructor(@inject('services.OmdapiService')protected omdbapiService: OmdapiService,)

Within the controller class, add the following code, which defines an endpoint that will be accept a movie or show title, call the omdbapi using our service, and return details of the movie or show:

@get('/omdbapi/details/{title}')//ts-lint:disable-next-line: no-anyasync getDetails(@param.path.string('title') title: string): Promise<any> {const titleArray: Array<string> = title.split(' ');const requestTitle: string = titleArray.join('+');console.log(`Calling OmdbApi Service for movie/show: ${title}`);return await this.callOmdbapi(requestTitle);}async callOmdbapi(title: string): Promise<any> {let apiKey: string = 'your-api-key';return await this.omdbapiService.getDetails(apiKey, title);}

Your controller should look like this:

Image for post
Image for post

(I placed my API key in an environment file for security purposes. You can simply hardcode your key for testing.)

In the terminal, start your application:

npm start

If your application starts successfully, navigate to http://127.0.0.1:3000/explorer/.

Select the /details endpoint and test by providing a movie or show title. Execute, and you should receive a response if everything goes well.

Image for post
Image for post

In case you ran into issues, feel free to clone this working version of the loopback application, https://github.com/DavidAMcIntosh/omdbapi.

(Request an API Key of your own from the omdbapi website. You need this to be able to make requests to the web service.)

I hope this helped. Until next time…

Interested in Computer Science, education and world domination.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store