Skip to content
intermediate Phase · REST API Development

OpenAPI / Swagger

Use OpenAPI specification to define and document REST APIs.

40m
0 problems
Topic Progress 0%

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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0 / 3 solved
Implement OpenAPI and Swagger

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
}
OpenAPI and Swagger Edge Cases

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, idempotency
OpenAPI and Swagger Testing Strategy

Write 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 injection

Quiz

1. What Spring Boot dependency enables OpenAPI documentation?

Question 1 options

2. What is the "Try it out" feature in Swagger UI?

Question 2 options

3. What is a common mistake when implementing OpenAPI and Swagger?

Question 3 options

Flashcards

Question

Spring Boot OpenAPI dependency?

Answer

springdoc-openapi-starter-webmvc-ui

Question

What does OpenAPI describe?

Answer

API endpoints, request/response formats, schemas, authentication

Question

OpenAPI and Swagger best practices

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