Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding swagger-UI with angular 10

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/

like image 501
Ankit Kumawat Avatar asked Jun 16 '26 01:06

Ankit Kumawat


1 Answers

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
        });
like image 123
Ankit Kumawat Avatar answered Jun 18 '26 15:06

Ankit Kumawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!