Integrate Swagger Editor in your UI

Vijay Bhosale
2 min readFeb 9, 2021

--

I was working on a low code platform which takes open API specification swagger or json as an input and generate java code or dot net core code as an output(with options of adding extra dependencies of course.!!)

Initially we were using swagger-hub for this but it allows max 4 swagger file edits at a time. Hence we decided to create our in house swagger editor. I was looking for swagger editors npm packages and found this. By looking at it, I knew I have to add this in my project but there was not enough documentation on how to do this. So, I am writing this blog for those who want to add this feature to their react app.

Install this module using — npm install swagger-editor

Add the below imports in your file -

import SwaggerEditor, {plugins} from ‘swagger-editor’;

import ‘swagger-editor/dist/swagger-editor.css’;

Now, in your render(), add below div with the exact id -

<div id=’swagger-editor’></div>

The next step is to initialize your editor with some defaults, you can do that by adding this code in your componentDidMount() -

window.editor = SwaggerEditor({ dom_id: ‘#swagger-editor’, layout: ‘EditorLayout’, plugins: Object.values(plugins), swagger2GeneratorUrl: ‘https://generator.swagger.io/api/swagger.json', oas3GeneratorUrl: ‘https://generator3.swagger.io/openapi.json', swagger2ConverterUrl: ‘https://converter.swagger.io/api/convert', });

We need to add necessary styles to our index.css file. Otherwise, embedded swagger-ui will not be able to scroll.

#swagger-editor { font-size: 1.3em;} .container { height: 100%; max-width: 880px; margin-left: auto; margin-right: auto;} #editor-wrapper { height: 100%; border: 1em solid #000; border: none;} .Pane2 { overflow-y: scroll;}

You are all set now. If you hit npm start, you will see below screen -

Now, we are able to edit swagger and see the changes runtime, it also has a build in drop zone so you can drop your swagger file and edit it, but how could we get the updated content out of it?

The trick here is, Swagger Editor uses local storage to store the editor content with a key - ‘swagger-editor-content’. You can easily get the updated contents from swagger editor by doing just —

localStorage.getItem(‘swagger-editor-content’);

Hope you find this helpful. :)

--

--

Vijay Bhosale
0 Followers

I am professional software engineer. I love JavaScript and like to solve new challenges.