How about OpenAPI descriptions and Swagger UI in your Java REST API?

I have this Quarkus project which uses basic JAX-RS annotations to generate your API, fairly basic and trivially simple. Yes that’s all Quarkus needs and it looks pretty much like Spring MVC or anything else. Now I’d need to create Postman test data and buid tests for all these endpoints or… or integrate it with Swagger – both to add OpenAPI style documentation AND to have a nice web GUI client to read infos and test them.

@GET
@Path("{for}")
public List<Events> getEvents(@PathParam("for") String for,
    @QueryParam("count") @DefaultValue("10") String count) {

There’s an exhaustive quickstart project explained on Quarkus site (read it first to see what dependency to add to your pom.xml) but I didn’t like how it puts all the documentation in one central point. I rather wanted to document the calls where they are defined, so I split the annotations.

First for the basic API information, I’ll use the @OpenAPIDefinition annotation. You can put it in just any class which only has to extend Application. I had a main class handy but it could be just any one.

import javax.ws.rs.core.Application;

@QuarkusMain
@OpenAPIDefinition(
    info = @Info(
        title = "Event API",
        version = "1.0",
        description = "A set of operations to gather and store event activity"))
public class EventMain extends Application {

And then, annotate your REST paths one by one with @Operation and @Parameter to generate descriptions.

@Path("/events")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class EventsApi {
@GET
@Path("{for}")
@Operation(summary = "Get events", description = "Get all events for a given instance")
public List<PostNoteEvent> getEvents(
      @Parameter(description = "The instance that needs to be analysed.") @PathParam("for") String for,
      @Parameter(
          description = "How many events back to be analysed, default 10.") @QueryParam("count") @DefaultValue("10") String count) {

All this will give you, when you connect to http://localhost:8080/swagger-ui a nice Swagger page which parses the /openapi endpoint it created especially for this:

That’s all folks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.