About cookies on this site Our websites require some cookies to function properly (required). In addition, other cookies may be used with your consent to analyze site usage, improve the user experience and for advertising. For more information, please review your options. By visiting our website, you agree to our processing of information as described in IBM’sprivacy statement. To provide a smooth navigation, your cookie preferences will be shared across the IBM web domains listed here.
Tutorial
Create REST APIs in minutes with LoopBack 4
Create a ToDo application that keeps track of to-do items using an in-memory database
On this page
LoopBack is a Node.js API framework that enables you to create APIs quickly that interact with backend resources like databases and services.
LoopBack 4, the next generation of LoopBack, includes:
- A brand new core rewritten in TypeScript that makes this framework simpler to use and easier to extend than ever
- Support for OpenAPI for comprehensive bottom-up and top-down REST API experience
- Enablement of instant GraphQL endpoints from REST APIs
In this lab, you will create a todo-list application that tracks to-do items using an in-memory database. You will experience how you can create REST APIs with just 5 steps:
- Scaffold a LoopBack 4 application
- Create the to-do model
- Define the datasource where the data is stored
- Add a repository to bind the model and datasource
- Add a controller to expose REST APIs
We will also show you how to expose GraphQL APIs from the same LoopBack application.
Set up
To complete the steps in this tutorial, you need to install Node.js and the LoopBack 4 command line interface (CLI).
Install Node.js version 14 or higher
See the Node documentation for installation instructions.
Install LoopBack 4 CLI
The LoopBack 4 CLI is a command-line interface that scaffolds an application as well as artifacts (for example, controllers, models, and repositories) for existing applications. The CLI provides the fastest and easiest way to get started with a LoopBack 4 project that adheres to best practices.
Install the CLI globally by running the following command:
Scaffold your to-do list application
To generate your application using the toolkit, run the lb4 app
command and fill out the on-screen prompts:
For this tutorial, when prompted with the options for enabling certain project features (loopback’s build, eslint, mocha, etc.), leave them all enabled.
Folder structure
After your application is generated, you will have a folder structure similar to the following:
Create the to-do model
In this section, you will use the LoopBack CLI to create a to-do model. To create the to-do list application, we need to create a to-do model that represents instances of a task on our to-do list. A model describes business domain objects and defines a list of properties with name, type, and other constraints.
In our application, the to-do model serves both as a data transfer object (DTO) for representing incoming to-do items (or instances) on requests, as well as our data structure for use with loopback-datasource-juggler.
The purpose of a to-do list is to track tasks. So, your application needs to let you label and differentiate between unique tasks, add extra information to describe those tasks, and finally, provide a way of tracking whether or not they’re complete.
The to-do model has the following properties:
id
: a unique idtitle
: a titledesc
: a description that details the specific task to be accomplishedisComplete
: a boolean flag for whether or not we’ve completed the task
We can use the lb4 model
command and answer the prompts to generate the model for us. Note that you should run this command within the newly created todo-list
directory. Press return
with an empty property name to generate the model.
Follow the in the CLI prompts:
And that's it! You created the to-do model and described it in TypeScript in src/models/todo.model.ts
. The update in index.ts
adds the todo.model.ts to the list of exported models.
Add a datasource
LoopBack uses datasources to connect to various sources of data, such as databases, APIs, message queues, and more. A datasource
in LoopBack 4 is a named configuration for a connector instance that represents data in an external system. The connector is used by legacy-juggler-bridge
to power LoopBack 4 repositories for data operations. For more information about datasources in LoopBack, see Datasources.
From inside the project folder, run the lb4 datasource
command to create a datasource. For the sake of simplicity, we use the in-memory database which persists the data in a local file system.
Since we have specified the file ./data/db.json
to persist the data for the in-memory connector, let's create the directory and file from the project's root and add in the values shown below using your favorite editor (vim for instance).
In the data/db.json
file, copy and paste the JSON below to give your model some data:
Now that you’ve added the datasource, let's move on to add a repository for the datasource.
Add a repository
A repository represents a specialized service interface that provides strong-typed data access (for example, CRUD) operations of a domain model against the underlying database or service. Learn more about Repositories in the LoopBack documentation.
From inside the project folder, run the lb4 repository
command to create a repository for your to-do model using the db
datasource from the previous step. The db
datasource shows up by its class name DbDataSource
from the list of available datasources.
The src/repositories/index.ts
file makes exporting artifacts central and also easier to import.
The newly created todo.repository.ts
class has the necessary connections that are needed to perform CRUD operations for our to-do model. It leverages the to-do model definition and 'db' datasource configuration and retrieves the datasource using Dependency Injection.
Next, we'll need to build a controller to handle our incoming requests.
Add a controller
In LoopBack 4, controllers handle the request-response lifecycle for your API. Each function on a controller can be addressed individually to handle an incoming request (like a POST request to /todos), to perform business logic and to return a response. In this respect, controllers are the regions where most of your business logic will live!
For more information about Controllers, see the LoopBack documentation.
You can create a REST controller using the CLI as follows:
The application is ready to run. Before that, let's review the code in TodoController
located in src/controllers/todo.controller.ts
. This example uses two new decorators to provide LoopBack with metadata about the route, verb, and format of the incoming request body:
@post('/todos')
creates metadata for@loopback/rest
so that it can redirect requests to this function when the path and verb match.@requestBody()
associates the OpenAPI schema for a Todo with the body of the request so that LoopBack can validate the format of an incoming request.- We’ve also added our own validation logic to ensure that a user will receive an error if they fail to provide a title property with their POST request.
Now that we’ve connected the controller, our last step is to tie it all into the application!
Put it all together
Let’s try out our application! First, you’ll want to start the app.
Next, you can use the http://localhost:3000/explorer
to browse your API and make requests!
Here are some requests you can try:
POST /todos
with a body of{ "title": "buy milk" }
.GET /todos/{id}
using the ID you received from yourPOST
, and see if you get your Todo object back.PATCH /todos/{id}
using the same ID with a body of{ "desc": "need milk for cereal" }
.GET /todos/{id}
using the ID from the previous steps to see that your changes are persisted.
That’s it! You’ve just created your first LoopBack 4 application.
Expose GraphQL APIs in LoopBack
The OpenAPI-to-GraphQL module is a new TypeScript module that creates a GraphQL wrapper for existing REST APIs which are described by the OpenAPI specification. IBM Research and the LoopBack team made it available in GitHub.
Follow these steps to expose the GraphQL APIs in your LoopBack application:
From your LoopBack application, run the following command to install OpenAPI-to-GraphQL and the required dependencies:
Next, you need to have your LoopBack application running. Make sure the LoopBack application is running in another terminal. To verify it is running, check for a confirmation message that it's running on port 3000. If not, run
npm start
. The OpenAPI spec generated by the todo-application is available athttp://localhost:3000/openapi.json
.Now you will use the
openapi-to-graphql
CLI to set up a GraphQL HTTP Server backed by express on port3001
. Specifying the OpenAPI spec generated by the todo-application as the parameter, start up the server by running the following command:npx
is a cool helper provided bynpm
and available out of the box since Node.js 8.x. Learn more in their announcement blog post: Introducing npx: an npm package runner.That’s it! You’re now ready to try out some tests and requests in the browser at
http://localhost:3001/graphql
.
Try out the GraphQL APIs
Before trying out queries, you can verfiy your model by pressing < Docs
in the top-right corner. You should get a Documentation Explorer. Under "Root Types", click on Query
from query: Query
. You should see the following:
If you click on the TodoWithRelations
from todoWithRelations(filter: FilterInputid: Float!): TodoWithRelations
or from todos(filter: Filter2Input): [TodoWithRelations]
, then you should see the following fields from earlier:
Once you've confirmed the fields are correct, you can go ahead and try the following:
To get all the to-do instances, run this
query
command:The expected output looks like this:
Create a to-do instance and retrieve its ID and title in the response object using the following
mutation
command:The expected output looks like this:
Retrieve the to-do instance created in the step above using the following command:
The expected output looks like this:
Conclusion
Congratulations! You have completed the lab.
You have successfully built and run a LoopBack microservice that is cloud-ready and can be deployed to IBM Cloud! Plus, in the bonus stage, you were able to expose LoopBack’s REST APIs in GraphQL using the new OpenAPI-to-GraphQL module and Express.