Adding Swagger UI to Angular App

Viewed 9863

Is there a good way to add the Swagger UI to an Angular app without getting too much in the weeds?

I'd like to add a reference to an API which is hosted on a different site, so all I need is the UI elements to reference the docs.

I found a package called Swangular-Components, but it seems to mess up my index.d.ts file. A solution like that would be the simplest for my situation, I think.

2 Answers

I've struggled with this numerous times but finally figured out somewhat of a solution mainly because I stumbled across this issue of adding swagger-editor to an angular project (https://stackoverflow.com/a/57431950/5641007). Had to tweak it a bit for swagger ui but ultimately got it working.

Install swagger-ui-dist

npm install swagger-ui-dist --save

Configure the angular.json file and desired component for swagger-ui.

// angular.json

"styles": [
    "node_modules/swagger-ui-dist/swagger-ui.css",
    "src/styles.css"
],
"scripts": [
    "node_modules/swagger-ui-dist/swagger-ui-bundle.js",
    "node_modules/swagger-ui-dist/swagger-ui-standalone-preset.js"
]
// component.ts

import { Component, OnInit } from '@angular/core';

declare const SwaggerUIBundle: any;

@Component({
  selector: 'app-swagger-ui',
  templateUrl: './swagger-ui.component.html',
  styleUrls: ['./swagger-ui.component.css']
})
export class SwaggerUiComponent implements OnInit {

  ngOnInit(): void {
    const ui = SwaggerUIBundle({
      dom_id: '#swagger-ui',
      layout: 'BaseLayout',
      presets: [
        SwaggerUIBundle.presets.apis,
        SwaggerUIBundle.SwaggerUIStandalonePreset
      ],
      url: 'https://petstore.swagger.io/v2/swagger.json',
      docExpansion: 'none',
      operationsSorter: 'alpha'
    });
  }
}
// component.html

<div id="swagger-ui"></div>

Github repo for example app: https://github.com/ostranme/angular-swagger-ui-example

Related