Excluding entities from Swagger model

Viewed 1592

We are using Swagger to model our API with Spring annotations:

@Operation(summary = "Creates a post for given user.")
@PostMapping("/post")
open fun createPost(
    @RequestParam("userId") user: User,
)

The issue we are having is that Swagger does not know there is a logic behind and we are only passing userId: Long for which the user is loaded by Hibernate.

The model of User contains several @OneToOne, @ManyToOne, @OneToMany relations to other entities and Swagger builds the model of User with all of them. This causes the model to be huge and some of our Swagger docs wouldn't even load in the browser as the model is in the size of megabytes.

Is there a way to tell Swagger:

  • to ignore specific entity/entities
  • to enforce different type (in this case Long)

Ideally something like:

@Operation(summary = "Creates a post for given user.")
@PostMapping("/post")
open fun createPost(
    @SwaggerType(Long::class)
    @RequestParam("userId") 
    user: User,
)
3 Answers

There are a few options that can be tried:

  1. Using inheritance with User Model, you can just define a SuperClass-childClass mapping with User class only containing the userId, and the child class that inherits from it will be holding the other attributes for you. In this way, the input will only be the userId with minimal effort.

  2. Using JsonIgnore, but this works really well while returning the response.

  3. With OpenAPI, Swagger has introduced the capability to use specific properties from the request class. More can be read from https://swagger.io/docs/specification/describing-request-body/

you can use two different class,a basic class and a senior class,and the senior extends the basic,use basic class in API;

or you can use @JsonIgnore if you don't want to show the field ,like:

@JsonIgnore
private String name;

Beacuse Swagger use jackson to json, if you shield the field by jackson,it will not appear.

In swagger you can use @ApiModelProperty(hidden = true),This is the perfect way

Related