Return to site

🧩📘 SWAGGER OPENAPI ANNOTATIONS EVERY JAVA DEV SHOULD KNOW

· java

🔸 TL;DR

Use Swagger/OpenAPI annotations to turn your Spring REST APIs into living documentation with zero extra UIs. Start with @Tag, @Operation, @Parameter, @ApiResponse, and @Schema to get clean docs, try-it-out, and accurate contracts. 🚀

Section image

🔸 WHY IT MATTERS

▪️ Faster onboarding & fewer “what does this endpoint do?” messages

▪️ Accurate, up-to-date API docs shipped with code

▪️ Better client integrations (codegen, tests, SDKs)

▪️ Clear contracts for versioning & backward compatibility

🔸 CHEAT SHEET (MOST-USED ANNOTATIONS)

▪️ @Tag — Group endpoints by feature/domain; adds a readable section in the UI.

▪️ @Operation — One endpoint story: summary, description, operationId, tags.

▪️ @Parameter — Document path/query/header params (name, example, required).

▪️ @ApiResponse — Describe outcomes (HTTP code, message, content schema).

▪️ @Schema — Model-level docs: field types, examples, constraints, enums.

🔸 MINI EXAMPLE (SPRING)

@Tag(name = "Orders", description = "Create and read customer orders")
@RestController
@RequestMapping("/api/orders")
class OrderController {

 @Operation(
 summary = "Get order by id",
 description = "Returns a single order with line items."
 )
 @ApiResponse(responseCode = "200", description = "Order found",
 content = @Content(schema = @Schema(implementation = OrderDto.class)))
 @ApiResponse(responseCode = "404", description = "Order not found")
 @GetMapping("/{id}")
 public OrderDto getOrder(
 @Parameter(description = "Order ID", example = "42")
 @PathVariable Long id) {
 // ...
 return null;
 }
}

class OrderDto {
 @Schema(example = "42")
 Long id;

 @Schema(description = "ISO-8601 creation date", example = "2025-11-08T09:30:00Z")
 String createdAt;

 @Schema(description = "Total amount in EUR", example = "129.90", minimum = "0")
 BigDecimal total;
}

🔸 TAKEAWAYS

▪️ Start small: add @Tag and @Operation to your controllers today.

▪️ Be generous with example and description—they cut support questions.

▪️ Use @ApiResponse for every expected HTTP code (200/201/400/404/422/500).

▪️ Keep DTOs annotated with @Schema to document fields where they live.

▪️ Treat docs as code: review them in PRs and evolve with versions.

#Swagger #OpenAPI #SpringBoot #Java #APIDesign #DeveloperExperience #DX #REST #Microservices #CleanCode #Documentation

Go further with Java certification:

Java👇

Spring👇

SpringBook👇