OpenAPI in Spring Boot
OpenAPI Annotations
@RestController
@RequestMapping("/api/products")
@Tag(name = "Products", description = "Product management APIs")
public class ProductController {
@Operation(summary = "Get product by ID",
description = "Retrieves a single product by its unique identifier")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "Product found",
content = @Content(schema = @Schema(implementation = Product.class))),
@ApiResponse(responseCode = "404", description = "Product not found")
})
@GetMapping("/{id}")
public ResponseEntity<Product> getProduct(
@Parameter(description = "Product ID") @PathVariable Long id) {
return ResponseEntity.ok(productService.getById(id));
}
@Operation(summary = "Create a new product")
@PostMapping
public ResponseEntity<Product> createProduct(
@Valid @RequestBody CreateProductRequest request) {
Product product = productService.create(request);
return ResponseEntity.status(201).body(product);
}
}
OpenAPI Structure
openapi: 3.0.0
info:
title: Product API
version: 1.0.0
paths:
/products:
get:
summary: List products
parameters:
- name: category
in: query
schema:
type: string
responses:
'200':
description: Product list
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Product'
components:
schemas:
Product:
type: object
properties:
id:
type: integer
name:
type: string
price:
type: number
Swagger UI Features
- Try it out — Execute requests from browser
- Schema viewer — Visualize data models
- Authentication — Test with auth tokens
- Download — Export OpenAPI spec
API Best Practices
Design Principles
- Use nouns, not verbs
- Plural resource names
- Consistent naming conventions
- Proper HTTP status codes
Versioning
- URI versioning (/v1/resource)
- Header versioning
- Deprecation policy
Documentation
- OpenAPI/Swagger specs
- Request/Response examples
- Error code documentation
- Rate limit documentation
Key Points
- Understanding OpenAPI and Swagger is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for OpenAPI and Swagger in a backend system. Consider scalability, error handling, and production readiness.
Solution
// OpenAPI and Swagger implementation
// Key aspects: validation, error handling, logging, testing
public class OpenAPIandSwagger {
// Production-ready implementation
}Identify and handle edge cases for OpenAPI and Swagger. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for OpenAPI and Swagger. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. What Spring Boot dependency enables OpenAPI documentation?
2. What is the "Try it out" feature in Swagger UI?
3. What is the primary purpose of OpenAPI and Swagger?
4. What is a common mistake when implementing OpenAPI and Swagger?
Flashcards
Question
Spring Boot OpenAPI dependency?
Click to reveal answer
Answer
springdoc-openapi-starter-webmvc-ui
Question
What does OpenAPI describe?
Click to reveal answer
Answer
API endpoints, request/response formats, schemas, authentication
Question
What is OpenAPI and Swagger?
Click to reveal answer
Answer
OpenAPI and Swagger is a key concept in backend development.
Question
When to use OpenAPI and Swagger?
Click to reveal answer
Answer
Use OpenAPI and Swagger when building production systems that require reliability, scalability, and maintainability.
Question
OpenAPI and Swagger best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Use @Operation, @ApiResponses, @Parameter annotations
- 2.springdoc-openapi auto-generates Swagger UI
- 3.OpenAPI 3.0 describes endpoints, schemas, authentication
- 4.Swagger UI enables interactive API testing
Interview Tips
- •Know how to add OpenAPI docs to Spring Boot
- •Explain OpenAPI spec structure
Cheat Sheet
OpenAPI/Swagger
- Dependency: springdoc-openapi-starter-webmvc-ui
- Annotations: @Operation, @ApiResponses, @Parameter
- Swagger UI:
/swagger-ui.html - OpenAPI Spec: paths, components, schemas, security