heidloff.net - Building is my Passion
Post
Cancel

Customization of REST APIs in LoopBack Applications

LoopBack creates automatically REST APIs for custom models (business objects) that are persisted. While this is helpful to get started quickly, for example in proofs of concepts or first iterations, the final APIs often have to be customized. LoopBack provides various ways to achieve this.

When I looked briefly at LoopBack for the first time a couple of weeks ago, my initial concern was that I don’t want to expose the ‘schema’ of my databases as REST APIs via the out of the box CRUD operations. However since then I’ve learned that LoopBack offers several mechanisms to define REST APIs exactly as you want to expose them.

Only for built-in models, e.g. User, and the custom models that extend ‘PersistedModel’ REST APIs for CRUD operations are generated. When you choose the model ‘Model‘ as base type, only the methods that you define and implement yourself (via remote methods) are exposed as REST APIs. This gives you maximal flexibility in terms of the design of your public interfaces. In the implementation of these methods you can use the Node.js APIs of the persisted models to manipulate the data in the underlying databases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "name": "MyModel",
  "base": "Model",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
  },
  "validations": [],
  "relations": {},
  "acls": [],
  "methods": {}
}

In addition to this you can customize the generated APIs in many ways:

I’ve implemented a sample with an additional method in a persisted model. I wanted to use most of the out of the box REST APIs for CRUD operations, but needed an additional method which returns not only one business object ‘ApprovalRequest’ but also the requester and approver ‘Person’ objects to minimize the amount of network requests between clients and the server.

Download the sample application from GitHub.

In approval-request.js the additional method is added, the actual implementation is done and the output model is defined. Here is a screenshot of the additional method in the API explorer.

image

Featured Blog Posts
Disclaimer
The postings on this site are my own and don’t necessarily represent IBM’s positions, strategies or opinions.
Trending Tags