Course – LS (cat=REST)

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

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we will briefly look at Swagger’s @Parameter and @Schema annotations. Furthermore, we will compare these annotations and identify the correct usage for each.

2. Key Difference

Simply put, @Parameter and @Schema annotations add different metadata to Swagger. The @Parameter annotation is for the parameters of an API resource request, whereas @Schema is for the properties of the model.

3. @Parameter

The @Parameter annotation is used for defining parameters in the parameters section of an operation or path. The @Parameter annotation helps to specify the name,  description, and example value of the parameter. Moreover, we can specify whether the parameter is required or optional.

Let’s look at its usage:

@RequestMapping(
    method = RequestMethod.POST, 
    value = "/createUser", 
    produces = "application/json; charset=UTF-8")
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
@Operation(summary  = "Create user",
    description = "This method creates a new user")
public User createUser(@Parameter(
                name =  "firstName",
                description  = "First Name of the user",
                example = "Vatsal",
                required = true) 
    @RequestParam String firstName) {
    User user = new User(firstName);
    return user;
}

Let’s look at the Swagger UI representation for our @Parameter example:

using parameter

Now, let’s look at @Schema.

4. @Schema

The @Schema annotation allows us to control Swagger-specific definitions such as description, name, type, example values, and allowed values for the model properties.

Also, it offers additional filtering properties in case we want to hide the property in certain scenarios.

Let’s add a few model properties to the User’s firstName field:

@Schema(
    description = "first name of the user", 
    name = "firstName", 
    type = "string", 
    example = "Vatsal")
String firstName;

Now, let’s take a look at the User Model’s specifications in Swagger UI:

using schema

5. Conclusion

In this quick article, we looked at two Swagger annotations we can use to add metadata for parameters and model properties. Then, we looked at some sample code using those annotations and saw their representations in Swagger UI.

As always, all these code samples are 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 open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.