Swagger
Introduction
Swagger is one of the popular type of documentation to show the api end point and test the result of end point which is just like a postman
Configuration
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-data-rest</artifactId>
<version>1.5.2</version>
</dependency>
// application.properties
// To define the uri of swagger
// To define the scope of getting controller information
springdoc.api-docs.path= /api-docs
springdoc.swagger-ui.path=/docs/index.html
springdoc.api-docs.enabled= true
springdoc.swagger-ui.enabled=true
springdoc.packages-to-scan= com.luv2code.demo.demo.controllers
@Configuration
public class SwaggerConfig implements WebMvcConfigurer {
@Value("${springdoc.swagger-ui.path:#{null}}")
private String springdocSwaggerUiPath;
// Define the setting swagger, such as title, security
@Bean
public OpenAPI reviewApiOpenApi()
{
final Info info = new Info() //
.title("Spring Security Swagger") //
.description("test Swagger") //
.version("v2");
return new OpenAPI() //
.components(new Components().addSecuritySchemes(
"BEARER_TOKEN",
new SecurityScheme()
.description("Please enter your SSO token. For SSO token, add the \"sso-\" prefix.")
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.in(SecurityScheme.In.HEADER)
.name("Authorization"))) //
.info(info);
}
// Define the path that can redirect to swagger url
@Override
public void addViewControllers(ViewControllerRegistry registry)
{
if (StringUtils.isNotEmpty(springdocSwaggerUiPath))
{
registry.addRedirectViewController("/docs", springdocSwaggerUiPath);
registry.addRedirectViewController("/docs/", springdocSwaggerUiPath);
}
}
}
Controller
Define a interface that need to be secured
@PreAuthorize("isAuthenticated()")
@SecurityRequirement(name = "BEARER_TOKEN")
@Validated
public interface IStandardApi
{
}
@RestController
@RequestMapping("/api/user")
@Tag(name = "UserController" , description = "the User API")
public class UserController implements IStandardApi{
@GetMapping(value = "/users")
@Operation(
summary = "Get all information of users",
responses = {
@ApiResponse(responseCode = "200", description = "Success"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "400", description = "Bad Request")
}
)
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
public List<UserInfo> getAllUser(){
List<UserInfo> userInfoList = userService.getUserList();
for (UserInfo userInfo : userInfoList) {
Link selfLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(this.getClass()).getUserInfoById(userInfo.getId())).withRel("Self");
userInfo.add(selfLink);
}
return userInfoList;
}
}
Result
Last updated
Was this helpful?