Course – LS (cat=REST) (INACTIVE)

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

>> CHECK OUT THE COURSE

1. Overview

We can use Swagger UI as a platform to visualize and interact with API interfaces in a convenient manner. It’s a powerful tool to generate API structures with minimal configuration required.

In this article, we’ll focus on using Swagger with Spring Boot REST APIs. Specifically, we’ll explore different ways to hide a request field in Swagger UI.

2. Introduction

For the sake of simplicity, we’ll create a basic Spring Boot application and explore the APIs using Swagger UI.

Let’s create a simple ArticleApplication using Spring Boot. We’re exposing two APIs using ArticlesController. We want to receive details related to all the articles using the GET API.

On the other hand, we use POST API to add details for a new article:

@RestController
@RequestMapping("/articles")
public class ArticlesController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("")
    public List<Article> getAllArticles() {
        return articleService.getAllArticles();
    }

    @PostMapping("")
    public void addArticle(@RequestBody Article article) {
        articleService.addArticle(article);
    }

}

We’ll use the Article class as a Data Transfer Object (DTO) for these APIs. Now, let’s add a few fields in the Article class:

public class Article {

    private int id;
    private String title;
    private int numOfWords;
    
    // standard getters and setters

}

We can access the Swagger UI at http://localhost:9090/springbootapp/swagger-ui/index.html#/articles-controller. Let’s run the application and see the default behaviour for the above two APIs:

API behavior application run

In the POST API, we accept all the details – namely, id, title, and numOfWords – from a user. In the GET API, we return the same fields in the response. We can see that by default, all the fields are shown by Swagger for both APIs.

Now, suppose we want to use a separate back-end logic to set the id field. In such a scenario, we don’t want the user to enter information related to the id field. To avoid any confusion, we want to hide this field in Swagger UI.

An immediate option that strikes our mind is creating a separate DTO and hiding the required fields in it. This method can be helpful if we want to add additional logic for DTOs. We can choose to use this option if it suits our overall requirements.

For this article, let’s use different annotations to hide fields in Swagger UI.

3. Using @JsonIgnore

@JsonIgnore is a standard Jackson annotation. We can use it to specify that a field is to be ignored by Jackson during serialization and deserialization. We can add the annotation to just the field to be ignored, and it’ll hide both getters and setters for the specified field.

Let’s give it a try:

@JsonIgnore
private int id;

Let’s rerun the application and examine the Swagger UI:hide getters and setters serialization and deserialization

We can see that the id field is not shown in the API descriptions. Swagger also provides annotations to achieve similar behaviour.

4. Using @Schema

@Schema annotation may be used to define a Schema for a set of elements of the OpenAPI spec, and/or to define additional properties for the schema. It is applicable e.g. to parameters, schema classes (aka “models”), properties of such models, request and response content, and header. We can use the hidden property of the annotation to hide a field in the definition of a model object in Swagger UI.

Let’s try it for the id field:

@Schema(hidden = true)
private int id;

In the above scenarios, we find that the id field is hidden for both GET and POST APIs. Suppose we want to allow users to view id details as part of the GET API response. In this case, we need to look for other options.

Swagger provides an alternative property, readOnly, as well. We can use it to hide the specified field during update operations but still show it for retrieval operations. However, the readOnly property is now deprecated and replaced by accessMode property:

Let’s examine it:

@Schema(accessMode = AccessMode.READ_ONLY)
private int id;

Let’s check the updated Swagger UI now:

Updated Swagger UI

We can see that the id field is visible for the GET API now but remains hidden for the POST API – it supports Read-Only operations.

Updated Swagger UI

5. Using @JsonProperty

Jackson provides the @JsonProperty annotation. We can use it to add metadata related to getters/setters of a POJO field that can be used during the serialization/deserialization of objects. We can set the access property of the annotation to allow only read operations on a particular field:

@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private int id;

In this manner, we’re able to hide the id field for the POST API model definition but can still show it in the GET API response.
Let’s explore another way to achieve the desired functionality.

6. Using @JsonView

Jackson also provides the @JsonView annotation that we can use to achieve the view restriction over fields of the class, and the same restrictions will be applicable in the Swagger UI.

Let’s create a Views class and create two views – Public and Private:

public class Views {
    public static class Public {}

    public static class Private {}
}

Next, let’s create a new Author class to which we’ll apply our restriction:

public class Author {

    @JsonView(Views.Private.class)
    private Integer id;

    @JsonView(Views.Public.class)
    private String name;

    @JsonView(Views.Public.class)
    private int email;

    // standard getters and setters

}

Here we have annotated the fields – name and email with @JsonView(Views.Public.class)  so that only these fields are included in the Public view.

Next, let’s apply the Public view over our GET method so that only the name and email will be visible in the Swagger UI:

@JsonView(Views.Public.class)
@GetMapping
public List<Author> getAllAuthors() {
    return authorService.getAllAuthors();
}

Let’s check the Swagger UI now:

Swagger UI

As we can see, only the email and name fields are visible in the Swagger UI.

For POST requests, we can also use @JsonView, but it works only in combination with @RequestBody and doesn’t support @ModelAttribute.

Let’s check an example with the POST request:

@PostMapping
public void addAuthor(@RequestBody @JsonView(Views.Public.class) Author author) {
  authorService.addAuthor(author);
}

Let’s check the updated Swagger UI now:

updated Swagger UI

We can see that the id field is not shown in the API descriptions, and only email and name are available to edit.

Let’s explore another way to achieve the desired functionality.

7. Using @Hidden

@Hidden is also a Swagger annotation that marks a given resource, class or bean type as hidden.

Let’s try it out:

@Hidden
private int id;

Let’s examine the Swagger UI specifications for this case:
get again
post request

We successfully hide the id field in both the GET & POST API request data definition.

7. Conclusion

We’ve explored different options to modify the visibility of model object properties in Swagger UI. The discussed annotations also offer several other features, which we can use to update the Swagger specifications. We should use the appropriate methods as per our requirements.

The source code is available on GitHub.

Course – LS (cat=REST)

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

>> CHECK OUT THE COURSE
res – REST (eBook) (cat=REST)
Comments are closed on this article!