Page Contents

Define the API from code-first approach

You may want to build your application from the ‘bottom up’ if you:

  • do not have a complete understanding of what your existing tools can offer.
  • want to capture already existing domain models so that they can be reflected as APIs for external consumption.
  • need to grow and change your API from the initial implementation
  • want to set up and run an API from an early stage of the production to easily envision the big picture of the end product.

There are various tools available to LoopBack which allows this bottom-up approach of building your application to be simple through the usages of metadata and decorators.

Start with LoopBack artfiacts

With TypeScript’s experimental decorator feature, APIs can be automatically built and exposed as your application continues development. Some key concepts utilize decorators to gather metadata about your code and then assemble them into a valid OpenAPI specification, which provide a description of your API. These concepts and their decorators include:

  • Model
    • @model()
    • @property()
  • Routes
    • @operation()
    • @param()

Define your models

Your models act as common definitions between data being handled by the API layer and the datasource layer. Since your API is going to be built around the manipulation of models and their properties, they will be the first to be defined.

First, write a simple TypeScript class describing your model and its properties:


export class Todo {
  id?: number;
  title: string;
  desc?: string;
  isComplete: boolean;

To this representation of your model, we can use the @model and @property decorators to create the model’s metadata; a model definition. LoopBack and LoopBack extensions can use this model definition for a wide variety of uses, such as:

  • generating OpenAPI schema for your APIs
  • validating instances of the models during the request/response lifecycle
  • automatically inferring relationships between models during datasource operations

To apply these decorators to your model, you simply prefix the class definition with the @model decorator, and prefix each property with the @property decorator:


import {model, property} from '@loopback/repository';

export class Todo {
  @property() id?: number;
    required: true,
  title: string;
  @property() desc?: string;
  @property() isComplete: boolean;

Define your routes