REST Top

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

>> CHECK OUT THE COURSE
Spring Top – Temp

Get started with Spring 5 and Spring Boot 2, through the reference Learn Spring course:

>> LEARN SPRING
Lightrun – Third Party Code

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

In this tutorial, we'll see how we can use Swagger annotations to make our documentation more descriptive. We'll learn how to add a description to different parts of the APIs, like methods, parameters, and error codes. We'll also see how to add request/response examples.

2. Project Setup

We'll create a simple Products API that provides methods to create and get products.

To create a REST API from scratch, we can follow this tutorial from Spring Docs to create a RESTful web service using Spring Boot.

The next step will be to set up the dependencies and configurations for the project. We can follow the steps in this article for setting up Swagger 2 with a Spring REST API.

3. Creating the API

First, we'll create our Products API and check the documentation generated.

3.1. Model

Let's define our Product class:

public class Product implements Serializable {
    private long id;
    private String name;
    private String price;

    // constructor and getter/setters
}

3.2.  Controller

Let's define the two API methods:

@RestController
@ApiOperation("Products API")
public class ProductController {

    @PostMapping("/products")
    public ResponseEntity<Void> createProduct(@RequestBody Product product) {
        //creation logic
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @GetMapping("/products/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable Long id) {
        //retrieval logic
        return ResponseEntity.ok(new Product(1, "Product 1", "$21.99"));
    }
}

When we run the project, the library will read all the paths being exposed and will create documentation corresponding to them.

Let's view the documentation at the default URL http://localhost:8080/swagger-ui/index.html:

Swagger Documentation

We can further expand the controller methods to look at their respective documentation. Next, we'll look at them in detail.

4. Making Our Documentation Descriptive

Now, let's make our documentation more descriptive by adding descriptions to different parts of the methods.

4.1. Add Description to Methods and Parameters

Let's look at a few ways to make the methods descriptive. We'll add descriptions to the methods, parameters, and response codes. Let's start with the getProduct() method:

@ApiOperation(value = "Get a product by id", notes = "Returns a product as per the id")
@ApiResponses(value = {
  @ApiResponse(code = 200, message = "Successfully retrieved"),
  @ApiResponse(code = 404, message = "Not found - The product was not found")
})
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(@PathVariable("id") @ApiParam(name = "id", value = "Product id", example = "1") Long id) {
    //retrieval logic
    return ResponseEntity.ok(new Product(1, "Product 1", "$21.99"));
}

@ApiOperation defines the properties of an API method. We have added a name to the operation using the value property and a description using the notes property.

@ApiResponses is used to override the default messages which accompany the response codes. For each response message we want to change, we need to add an @ApiResponse object.

For example, let's say the product is not found, and our API returns HTTP 404 status in this scenario. If we do not add a custom message, the original message “Not found” can be hard to understand. The caller may interpret it as the URL is wrong. However, adding a description that “The product was not found” makes it clearer.

@ApiParam defines the properties of method parameters. It can be used along with the path, query, header, and form parameters. We have added a name, a value(description), and an example for the “id” parameter. If we didn't add the customization, the library would only pick up the name and type of the parameter, as we can see in the first image.

Let's see how this changes the documentation:

Here, we can see the name “Get a product id” alongside the API path /products/{id}. We can also see the description just below it.  Additionally, in the Parameters section, we have a description and an example for the field id. And finally, in the Responses section, we can notice how the error descriptions for 200 and 404 codes have changed.

4.2. Add Description and Examples to the Model

We can make similar improvements in our createProduct() method. In addition, since the method accepts a Product object, it makes more sense to provide the description and examples in the Product class itself.

Let's make some changes in the Product class to achieve this:

@ApiModelProperty(notes = "Product ID", example = "1", required = true) 
private Long id; 
@ApiModelProperty(notes = "Product name", example = "Product 1", required = false) 
private String name; 
@ApiModelProperty(notes = "Product price", example = "$100.00", required = true) 
private String price;

@ApiModelProperty annotation defines the properties of the fields. We have used this annotation on each field to set its notes (description), example, and required properties.

Let's restart the application and take a look at the documentation of our Product model again:

If we compare this to the original documentation image, we find that the new image contains examples, descriptions, and red asterisks(*) to identify the required parameters.

By adding examples to models, we can automatically create example responses in every method which uses the model as an input or output. For example, from the image corresponding to the getProduct() method, we can see that the response contains an example containing the same values we provided in our model.

Adding examples to our documentation is important because it makes value formats even more precise. If our models contain fields like date, time, or price, an exact value format is necessary. Defining the format beforehand makes the development process more effective for both the API provider and the API clients.

5. Conclusion

In this article, we looked at different ways to improve the readability of our API documentation. We learned how to document methods, parameters, error messages, and models using the annotations @ApiParam, @ApiOperation, @ApiResponses, @ApiResponse, and @ApiModelProperty.

As always, the code for these examples is available over on GitHub.

Spring bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> THE COURSE
REST bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course :

>> CHECK OUT THE COURSE
REST footer banner
1 Comment
Oldest
Newest
Inline Feedbacks
View all comments
Comments are closed on this article!