We're going to show how to access 3rd party REST APIs using LoopBack OpenAPI connector in LoopBack 4 application. The Swagger Petstore REST APIs http://petstore.swagger.io:8080/ will be used in this example. Make sure you run the following steps in an existing LB4 application.
The OpenAPI spec for the Petstore is located at: http://petstore.swagger.io:8080/api/v3/openapi.json. Instead of using URL directly, we need to modify the server
property of the OpenAPI spec. Otherwise, the error 500 Error: only absolute urls are supported error.
will occur.
petstore.json
at the root directory of the project.petstore.json
, find the servers
property and modify:"servers": [{"url": "/api/v3"}],
to
"servers": [{"url": "http://petstore.swagger.io:8080/api/v3/"}],
Run the DataSource generator with the OpenAPI connector.
$ lb4 datasource
? Datasource name: ds
? Select the connector for ds: OpenAPI (supported by StrongLoop)
? HTTP URL/path to Swagger spec file (file name extension .yaml/.yml or .json):
petstore.json
? Validate spec against Swagger spec 2.0?: No
? Security config for making authenticated requests to API:
? Use positional parameters instead of named parameters?: No
create src/datasources/ds.datasource.config.json
create src/datasources/ds.datasource.ts
Run the Service generator with the Remote service proxy backed by a data source
option.
$ lb4 service
? Service type: Remote service proxy backed by a data source
? Please select the datasource DsDatasource
? Service name: PetStoreService
create src/services/pet-store-service.service.ts
update src/services/index.ts
Service PetStoreService was created in src/services/
In this example, the PetStoreService maps to two of the endpoints / operations in the OpenAPI spec: addPet
and getPetById
.
In src/services/pet-store-service.service.ts
, we are going to add two functions in the PetStoreService
interface. The corresponding classes for the return types are created.
Run lb4 controller
command.
$ lb4 controller
? Controller class name: PetStore
Controller PetStore will be created in src/controllers/pet-store.controller.ts
? What kind of controller would you like to generate? Empty Controller
create src/controllers/pet-store.controller.ts
update src/controllers/index.ts
Controller PetStore was created in src/controllers/
In src/controllers/pet-store.controller.ts
:
Add a constant PetSchema
which will be used when defining the endpoints.
export const PetSchema = {
type: 'object',
required: ['id'],
properties: {
id: {type: 'number'},
name: {type: 'string'},
},
};
Inject the PetStoreService
export class PetStoreController {
constructor(
@inject('services.PetStoreService')
protected petStoreService: PetStoreService,
) {}
// ...
}
Add the two functions createPet
and findPetById
.
See src/controllers/pet-store.controller.ts
for details.