How to add Swagger to Quarkus

How to add Swagger to Quarkus

OpenAPI or Swagger specification is the de facto standard for creating REST APIs. Almost every developer expects to see some Swagger documentation when works with APIs or doing integration. Apps made with Quarkus are not exceptions either. In this article, I go through how to add Swagger to Quarkus apps.

In the past two articles, we’ve covered how to create REST APIs and how to use MySQL with Quarkus. We implemented CRUD functionality for the User resource that persists data to a MySQL database. The next step is to create API documentation for it.

Fortunately, the process is rather straightforward in Quarkus thanks to smallrye-openapi library. So let’s begin.

Add Open API dependency

The very first step is to add the quarkus-smallrye-openapi to the project. This library is built on top of the Eclipse MicroProfile OpenAPI specification. It generates OpenAPI dynamic schema and also has built-in Swagger UI.

Now if you run the code and go to /openapi, you should be able to download the specification in YML format. To change the path, add this configuration to application.properties,

Creating SwaggerConfig

We don’t necessarily need to have this file, but it’s highly recommended. It contains annotations that provide information about the APIs purpose, maintainer, licensing, etc. Note that to make the annotations working, the SwaggerConfig.java file should extend Application from javax.ws.rs.core.Application. That’s odd but necessary. Since the class is for the configuration only, it doesn’t require any implementation. An example of it would be like this,

Enabling Swagger UI

Let’s enable the Swagger UI before proceeding further. For that open application.properties file and enable Swagger UI as follows,

After that, Swagger UI is accessible at /swagger-ui.

To provide a custom path, just override this parameter,

Document the APIs

For many developers, plain Swagger documentation is good enough. Though, in complex projects where many business terminologies are used, having more documented APIs are highly appreciated. One can achieve that by applying a set of annotations on controllers. In our case, we can enrich the User APIs with details such as status codes, description of APIs, and required fields as follows,

Check here to see a list of existing annotations.

Fully functional example

As usual, you can find the fully functional example on my GitHub page at the link below,

https://github.com/kasramp/quarkus-rest-example

Thanks for reading and hope you’ve learned how to add Swagger to your Quarkus app.

Inline/featured images credits