API / Swagger Interview questions
How do you use Swagger annotations in a Java Spring Boot application?
In a Spring Boot application, Swagger/OpenAPI documentation is typically generated automatically from annotated controller code using a library like springdoc-openapi, rather than hand-writing the YAML/JSON spec separately and keeping it in sync manually.
@RestController @RequestMapping("/users") @Tag(name = "Users", description = "User management operations") public class UserController { @Operation(summary = "Get a user by ID") @ApiResponse(responseCode = "200", description = "User found") @ApiResponse(responseCode = "404", description = "User not found") @GetMapping("/{id}") public User getUser(@Parameter(description = "User ID") @PathVariable Long id) { return userService.findById(id); } }
Annotations like @Tag, @Operation, @Parameter, and @ApiResponse (from the io.swagger.core.v3 package that springdoc-openapi builds on) let a developer add documentation metadata directly alongside the actual endpoint code, so the two stay physically close together and are far less likely to silently drift apart over time.
Once the library is on the classpath, it scans annotated controllers at application startup and exposes a live-generated OpenAPI document (typically at /v3/api-docs) along with an embedded Swagger UI (typically at /swagger-ui.html), with no separate manual spec file required unless the team specifically wants one.
More Related questions...