Search code examples
javascriptrestswaggerloopback

How to use a swagger.json client with loopback?


When starting a LoopBack application and browsing to its explorer view, I can clearly see it uses swagger behind the scenes. (Even the explorer interface looks like derived from swagger UI.)

Swagger This explorer component shouldn't be used in production. But the exposed swagger.json path is inside explorer. What I want to do is to expose a swagger.json of an existing LoopBack API, so that I can integrate any swagger based client (like Swagger-js) at the front-end level.

LoopBack includes ways to generate API using Swagger specifications with swagger generator. It also includes the facility to connect to existing APIs with swagger specifications. These are out of my question.


Solution

  • Finally I figured out how to do it myself.

    First, there is a command to export swagger.json. See: Documentation
    lb export-api-def --json -o \"./client/swagger.json\"
    This will save the swagger.json in the client folder.
    Since it is a little long, I added it to npm scripts:
    "swagger": "lb export-api-def --json -o \"./client/swagger.json\""

    Then we have to setup loopback server to serve static files so that we can expose swagger.json. See: Static Middleware

    "files": {
      "loopback#static": {
        "params": "$!../client"
      }
    }
    

    Now, since there's a URL available for swagger.json, a swagger client can be used to access the API.
    var swaggerClient = new SwaggerClient(specUrl);