Sub topic 7
Annotating controllers and operations with @Tag and @Operation
This chapter assumes you can write Spring MVC controllers, that springdoc-openapi is already on your classpath, and that /v3/api-docs and Swagger UI respond. Without annotations, springdoc builds a usable document from your mappings. The result is bare. Operations get names such as getBook, and every controller becomes a group called book-controller. The annotations in this chapter turn that output into documentation a client developer can read.
What springdoc infers and what it cannot
For each handler method, springdoc reads the request mapping, the parameter types, and the return type. It can therefore produce the path, the HTTP method, the parameters, and a default 200 response. It cannot know the purpose of an endpoint, the cases where it returns a 404, or how your team groups its resources.
The Swagger annotations in the io.swagger.v3.oas.annotations packages fill in that missing information. They only affect the generated description. They do not change how requests are handled at runtime.
| Annotation | Placed on | Controls |
|---|---|---|
| `@Tag` | Controller class (or method) | The group heading in Swagger UI and its description |
| `@Operation` | Handler method | Summary, description, operation id, deprecation |
| `@ApiResponses` / `@ApiResponse` | Handler method | Documented status codes and their payloads |
| `@Parameter` | Method parameter | Description, example, required flag |
How the pieces map to the document
The diagram shows where each annotation lands in the generated OpenAPI document.
Grouping endpoints with @Tag
@Tag on a controller class names the group that Swagger UI shows as a collapsible section. Without it, springdoc derives the name from the class, for example book-controller.
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
@Tag(name = "Books", description = "Operations on the book catalog")
public class BookController {
// handler methods
}The name becomes the tag name that each operation references. The description appears next to the heading in the UI.
You can also put @Tag on a single method. An operation can then belong to a different group than the rest of its controller. A method-level tag is added to the class-level tag, so the operation shows up under both. If you want an operation to appear in one group only, avoid mixing class-level and method-level tags on the same controller.
Keep tag names identical across controllers when they should share a group. Two controllers that both declare @Tag(name = "Books") merge into a single section. A typo such as "Book" creates a second section.
Describing an operation with @Operation
@Operation documents one handler method. These attributes are the ones you will use most:
summary: a short title shown in the collapsed row in Swagger UI. Keep it under about 60 characters.description: longer text, which Markdown can format. Use it for behavior that the summary cannot carry.operationId: a unique identifier. Client generators use it as the method name.deprecated: marks the operation as deprecated in the document.tags: assigns tag names from the method, as an alternative to@Tag.
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/books")
@Tag(name = "Books", description = "Operations on the book catalog")
public class BookController {
private final BookService service;
public BookController(BookService service) {
this.service = service;
}
@Operation(summary = "Get a book by id", description = "Returns one book, or 404 if it does not exist.")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Book found"),
@ApiResponse(responseCode = "404", description = "Book not found", content = @Content)
})
@GetMapping("/{id}")
public Book getBook(
@Parameter(description = "Book identifier", example = "42") @PathVariable long id) {
return service.findById(id);
}
}In the generated document, this method becomes GET /api/books/{id} with the summary and description you wrote. It lists two responses and a path parameter described as "Book identifier" with the example 42.
The default operation id
When you omit operationId, springdoc uses the Java method name. If two methods in different controllers share a name, it appends a numeric suffix, for example getBook_1. The suffix changes if you reorder or add methods, and a generated client then renames its methods. Set operationId explicitly on any operation that a client generator consumes.
@Operation(operationId = "getBookById", summary = "Get a book by id")
@GetMapping("/{id}")
public Book getBook(@PathVariable long id) {
return service.findById(id);
}Operation ids must be unique across the whole document. Duplicates are not rejected by springdoc, but many tools refuse such a document.
Documenting responses
Declaring responses with @ApiResponses is the part of controller documentation that readers value most. Springdoc already adds the 200 response from the return type. The annotation lets you add the error cases that the method signature does not reveal.
Three details cause most mistakes:
- Empty body. For a 404 with no payload, write
content = @Content. An@ApiResponsewithoutcontentinherits the schema of the method's return type, so the document would claim that a 404 returns aBook. - Code matching. The
responseCodeis a string, such as"404". It is only documentation. Nothing checks that the method actually returns that status. - Overriding the default. If you declare
"200"yourself, your description replaces the generated one. The schema is still taken from the return type unless you setcontent.
For a method that returns a different status on success, declare it explicitly and keep it in line with @ResponseStatus or ResponseEntity:
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseStatus;
@Operation(summary = "Delete a book")
@ApiResponse(responseCode = "204", description = "Book deleted")
@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/{id}")
public void deleteBook(@PathVariable long id) {
service.delete(id);
}Springdoc reads @ResponseStatus, so the document already shows 204 here. The explicit @ApiResponse adds the description. The later chapter on responses and error payloads covers shared error models in depth.
Deprecating and hiding operations
Setting deprecated = true on @Operation marks the operation in the document, and Swagger UI shows it struck through. Spring's @Deprecated annotation on the method has the same effect. Use one of them, not both, so that the intent has a single source.
@Operation(summary = "Find a book by title", deprecated = true,
description = "Use GET /api/books?title= instead.")
@GetMapping("/by-title/{title}")
public Book findByTitle(@PathVariable String title) {
return service.findByTitle(title);
}Removing an operation from the document entirely is a separate topic, covered in the chapter on hiding endpoints.
Common errors
- Annotations from the wrong package. The
@Tagand@Operationannotations come fromio.swagger.v3.oas.annotations. Older Swagger 2 annotations such as@Apiand@ApiOperationinio.swagger.annotationsare ignored by springdoc. - Two sections for one resource. Tag names are compared as exact strings.
Booksandbooksproduce separate sections. - Wrong 404 schema. Forgetting
content = @Contenton an error response makes the document describe the success type for it. - Documentation drifting from behavior. Because status codes are free text, a changed method can silently contradict its annotations. The testing chapter shows how to catch this in an automated check.
- Long annotations hiding the logic. If annotations grow larger than the method body, move shared ones to a custom meta-annotation or a documentation interface that the controller implements.
Check your understanding
Exercise
A controller has @Tag(name = "Books") on the class and @Tag(name = "Admin") on one method. Which tags does that method's operation have in the generated document, and what would you change to place it only under "Admin"?
Show answer
The operation has both "Books" and "Admin", because the method-level tag is added to the class-level tag. To place it only under "Admin", move the method to a separate controller tagged "Admin", or remove the class-level @Tag and tag each method individually.
Exercise
You add @ApiResponse(responseCode = "404", description = "Book not found") to a method that returns Book. Swagger UI shows a Book schema for the 404 response. What is the fix?
Show answer
Add content = @Content to the annotation. An empty @Content tells springdoc the response has no body, so it does not copy the return type's schema.