How to hide an endpoint in Springdoc OpenAPI

How to hide an endpoint in Springdoc OpenAPI

Springdoc OpenAPI is the best library for documenting APIs on Spring Boot applications. It is an almost drop and replacement of now the defunct SpringFox Swagger library since they share many similarities. Previously, we covered how to get started with Springdoc OpenAPI and disable the OpenAPI in a production environment. In this article, we focus instead on how to hide an endpoint in Springdoc OpenAPI.

The approach is pretty straightforward as one needs to use the @Hidden annotation, which is a Swagger annotation for the OpenAPI 3 specification. Let’s say, we have an endpoint that we intend to hide as follows:

@RestController
@RequestMapping("/v1/hidden")
public class HiddenController {

  @GetMapping("/test")
  @ResponseStatus(HttpStatus.OK)
  @Hidden
  public ResponseEntity<TestResponse> getTestResponse() {
    return ResponseEntity.ok(new TestResponse(Map.of("key1", "value1")));
  }

  public record TestResponse(Map<String, String> data) {

  }
}
Hide endpoint

To hide the endpoint, we can add the @Hidden annotation:

@GetMapping("/test")
@ResponseStatus(HttpStatus.OK)
@Hidden
public ResponseEntity<TestResponse> getTestResponse() {
  return ResponseEntity.ok(new TestResponse(Map.of("key1", "value1")));
}

Hiding only the schema

There are scenarios in which we need to only hide the schema or the response data model. For example, we would like to only hide the TestResponse schema from the Swagger UI.

Hide schema

To achieve that, we can add the @Content(schema = @Schema(hidden = true)) expression inside the @ApiResponse annotation.

@GetMapping("/test")
@ResponseStatus(HttpStatus.OK)
@ApiResponses(value = {@ApiResponse(responseCode = "200", content = @Content(schema = @Schema(hidden = true))) })
public ResponseEntity<TestResponse> getTestResponse() {
  return ResponseEntity.ok(new TestResponse(Map.of("key1", "value1")));
}

Conclusion

In this article, we discussed how to hide an endpoint in Springdoc OpenAPI. Additionally, we covered another approach known as the hiding data model, in which we can specifically target not displaying the schema. This approach is useful for making the Swagger UI less cluttered and easy to navigate. The downside is that the response is unknown to developers without trying the endpoint.

Inline/featured images credits

2348 2363 2387