Adding swagger-UI with angular 10
Asked Answered
C

1

8

How to add Swagger UI in your angular application?

I have searched numerous times for this question and found only one solution is there and It was done using swagger-ui-dist package but in the latest release of the https://www.npmjs.com/package/swagger-ui tells that use swagger-ui instead of swagger-ui-dist for single-page applications.

There is a solution of adding this package to react and it is well explained.

Swagger-UI with React - https://swagger.io/blog/api-documentation/building-documentation-portal-swagger-tutorial/

Chasseur answered 23/12, 2020 at 4:36 Comment(0)
C
13

I implemented this functionality in my angular application and thought that it can be helpful for other developers as well. I have searched it at multiple places and read multiple blogs.

Steps -

  1. install swagger-ui

    npm i swagger-ui

  2. Configure the angular.json file and swagger-ui CSS module to it.

  "styles": [ "./node_modules/swagger-ui/dist/swagger-ui.css"]
  1. Add the import statement of swagger-UI to your component.ts file.

    import SwaggerUI from 'swagger-ui';

  2. Add the below code in your component's ngOnInit.

// example-swagger-exp.component.ts
ngOnInit() {
     SwaggerUI({
         domNode: document.getElementById('swagger-ui-item'),
         url: 'https://petstore.swagger.io/v2/swagger.json'
       });
 }
  1. last part of this functionality, Add the below code to the HTML file of your component

    // swagger-exp.component.html

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

Note - One last important thing,

How can you add your swagger.json/swagger.yaml object in step 4?

Simply replace the 'url' parameter with 'spec' and add your JSON object.

      SwaggerUI({
          domNode: document.getElementById('api-data'),
          spec : your json object
        });
Chasseur answered 23/12, 2020 at 4:36 Comment(2)
I would like to add that styles could be included into component styles (not project root) with simple @import "swagger-ui/dist/swagger-ui.css" this allows also to setup the documentation module as lazy loadedAtropos
Nice comment @blazkovicz. It works well importing css direclty in Angular component who calls SwaggerUI({...}). Only one more change to make it work on my side : add encapsulation: ViewEncapsulation.None on Angular component definition.Wandawander

© 2022 - 2024 — McMap. All rights reserved.