Advertisements

Continued from:

MicroProfile Open API 

For an API, defining a contract is necessary, it will contain the rules and details for consuming the API. In the restful API, OpenAPI (swagger) has become the most used contract for that purpose. Right out of the box, MicroProfile provides support to Open API and generates a YAML file with the details of our Restful services; and we can see it at /openapi endpoint.

Open API allows us to add more details to our Restful resources like descriptions, status codes, return examples, details of parameters, and more by adding some annotations in our code. Let’s see an example using the findById method into the BookResource class in the items-service application.

Advertisements
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@APIResponses(
   value = {
   @APIResponse(
      responseCode = "404",
      description = "Book not found"),
   @APIResponse(
      responseCode = "200",
      description = "Book is found and returned",
      content = @Content(schema = @Schema(implementation = Book.class)))
})
@Operation(
   summary = "Finds a book by its Id",
   description = "Finds a book by its Id … more details…")
public Book findById(
 @Parameter(description = "Book's Id", required = true) @PathParam("id") Long id) {
   return service.findById(id).orElseThrow(NotFoundException::new);
}

Then, I recommend adding the following dependency to provide a Swagger-UI page displaying the details into our openapi.yaml file. 

<dependency>
    <groupId>org.microprofile-ext.openapi-ext</groupId>
    <artifactId>swagger-ui</artifactId>
    <version>1.0.3</version>
    <scope>runtime</scope>
</dependency>

It’s time to see the documentation of our Resources, so we just need to access the endpoint /<appcontext>/api/openapi-ui. In our case, http://localhost:8080/items-service/api/openapi-ui

documentation of our Resources
Table of contents:

Advertisements

Pages: 1 2 3 4 5 6 7 8

Leave a Reply

Your email address will not be published. Required fields are marked *