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/

1 Answer 1

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
        });
Sign up to request clarification or add additional context in comments.

2 Comments

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 loaded
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.