Step 1: SpringDoc OpenAPI Integration – Spring Documentation Series

πŸ“– Step 1: SpringDoc OpenAPI Integration

πŸŽ₯ YouTube Video: Coming Soon – Subscribe to JavaiOS Channel


Test RESTful API with SpringDoc Swagger UI πŸ“–

This blog outlines the full journey of integrating, adjusting, and testing Swagger UI for the AdventureTube microservices system using SpringDoc, Spring Cloud Gateway, and finally with Postman. The work is structured into five major phases for complete API documentation and testing workflow.


🎯 Benefits of Full Swagger UI and Postman Integration

With these processes, you will have different aspects of benefit like below:

1. As a Producer of API πŸ—οΈ

  • Your documentation will be exposed with a very clean convention that you may not even need to create separate documentation to explain your API.
  • You are also able to test your own API partially or fully automated depending on the process you’ve made. If you utilize Jenkins and n8n AI agent together (which I haven’t seen yet in examples online), it could be an enormous time saver with a strong test process in your CD/CI pipeline.
  • You will have a centralized single place where all your APIs are documented and visible, helping you easily manage, update existing APIs, and design new APIs consistently and efficiently.

2. As a Consumer of API πŸ”§

  • You will be able to access and understand the actual usage of the API much easier and faster, and even test it immediately to give you an instant start to work.
  • You will have realistic example data available directly in the API docs, making it much simpler to craft correct requests without guessing formats.
  • You can easily import the API into Postman collections using real examples, making early validation of API behaviors fast without needing backend development knowledge.

βœ… And at the end of this process:
No matter how perfectly you build an API, if it’s not easily accessible, testable, and understandable, there is no true point in building it.

This setup transforms your API from a theoretical backend resource into a real-world usable and valuable service.


πŸš€ Phase 1: Setup Swagger UI and OpenAPI Aggregation

Configured SpringDoc in each microservice (auth-service, member-service, web-service, geo-service) using a centralized configuration managed by Spring Cloud Config.

Instead of configuring application.yml separately in each microservice, added the following settings in the centralized config files (config-service/src/main/resources/config/*.yml):

springdoc:
  api-docs:
    path: /v3/api-docs
  swagger-ui:
    path: /swagger-ui.html

βœ… This approach ensures centralized management of SpringDoc and Swagger properties for all services, minimizing duplication and making future updates easier.

In the Gateway Service, configured multiple sub-service documentation endpoints under application.yml to aggregate all APIs into the central Swagger UI:

springdoc:
  swagger-ui:
    enabled: true
    path: /swagger-ui.html
    urls:
      - name: Auth Service
        url: /auth-service/v3/api-docs
      - name: Member Service
        url: /member-service/v3/api-docs
      - name: Web Service
        url: /web-service/v3/api-docs
      - name: Geospatial Service
        url: /geo-service/v3/api-docs

βœ… This configuration allows Swagger UI at the API Gateway to display all sub-service APIs together in one portal:
https://api.adventuretube.net/swagger-ui/index.html

You can verify if Spring Cloud Config correctly applied the settings by checking:

  • πŸ”Ή https://config.adventuretube.net/auth-service/native
  • πŸ”Ή Validate that springdoc.api-docs.path and springdoc.swagger-ui.path are properly loaded.

βœ… Result:

  • Swagger UI is available centrally
  • All microservices’ API docs are exposed via the Gateway
  • Configuration is controlled from one place (Spring Config Server)

πŸ”’ Phase 2: Adjust Gateway and Microservice Security for Swagger Access

Integration steps for proper security configuration:

  • Integrated a global AuthenticationFilter at the Gateway
  • Whitelisted Swagger UI paths and /v3/api-docs/** using RouterValidator
  • Updated Spring Security in each service to permit access to Swagger paths
  • Gateway RouteLocator correctly routed API docs without security blocking

βœ… Result: Swagger UI loaded without errors but still showed internal IP addresses.

These are brief explanations for what you have to do but don’t include any explanation of why. So in order to understand why, you need to understand the Spring Security mechanism that is applied in AdventureTube. πŸ‘‰ Check out the detailed Spring Security blog here.


🌐 Phase 3: Centralize Swagger UI Access via API Gateway

Problem Identification

Swagger UI listed API servers using internal IPs and ports, making testing difficult and exposing internal infrastructure.

Solution Implementation

Added @OpenAPIDefinition in each microservice to override server URL:

@OpenAPIDefinition(
    servers = {
        @Server(url = "https://api.adventuretube.net", description = "AdventureTube API Gateway")
    }
)
public class AuthServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuthServiceApplication.class, args);
    }
}

βœ… Result: All APIs now routed through https://api.adventuretube.net without IP exposure.


πŸ§ͺ Phase 4: Create Realistic API Examples for Instant Testing

Added @ExampleObject to all major API endpoints to provide realistic testing data.

Example Implementation for Signup API

@Operation(
    summary = "Signup user",
    requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
        content = @Content(
            mediaType = "application/json",
            examples = @ExampleObject(
                name = "Signup Example",
                value = """
                {
                  "googleIdToken": "<Google ID Token>",
                  "refreshToken": "ref-token",
                  "email": "strider@gmail.com",
                  "password": "123456",
                  "username": "striderlee",
                  "role": "USER",
                  "channelId": "UC_x5XG..."
                }
                """
            )
        )
    )
)
@PostMapping("/signup")
public ResponseEntity<AuthResponse> signup(@RequestBody SignupRequest request) {
    // Implementation
}

Example for Authentication API

@Operation(
    summary = "Authenticate user and issue tokens",
    requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
        content = @Content(
            mediaType = "application/json",
            examples = @ExampleObject(
                name = "Login Example",
                value = """
                {
                  "email": "strider@gmail.com",
                  "googleIdToken": "<Google ID Token>",
                  "googleId": "12345"
                }
                """
            )
        )
    )
)
@PostMapping("/token")
public ResponseEntity<AuthResponse> issueToken(@RequestBody AuthRequest request) {
    // Implementation
}

βœ… Result: Developers can now test APIs immediately with realistic data without guessing request formats.


πŸ“‹ Phase 5: Export to Postman for Advanced Testing

Postman Integration Workflow

  1. Export OpenAPI Specification
    • Access Swagger UI at https://api.adventuretube.net/swagger-ui/index.html
    • Download OpenAPI JSON specification for each service
    • Alternative: Use direct API endpoint /v3/api-docs
  2. Import into Postman
    • Open Postman β†’ Import β†’ Link/File
    • Import the OpenAPI specification
    • Postman automatically creates collection with all endpoints
  3. Configure Environment Variables
    • Create Postman environment for AdventureTube
    • Set base URL: https://api.adventuretube.net
    • Add authentication tokens as variables

Automated Testing Benefits

  • Pre-request Scripts – Automatically obtain authentication tokens
  • Test Scripts – Validate response status, structure, and data
  • Collection Runner – Execute entire API test suites
  • Newman Integration – Run tests in CI/CD pipelines

🎯 Complete Implementation Checklist

SpringDoc Configuration βœ…

  • βœ… Centralized SpringDoc configuration via Spring Cloud Config
  • βœ… Gateway aggregation of all microservice documentation
  • βœ… Proper API documentation paths configured
  • βœ… OpenAPI 3 specification generation

Security Integration βœ…

  • βœ… Swagger paths whitelisted in security configuration
  • βœ… Gateway authentication filter bypass for documentation
  • βœ… Microservice security permits Swagger access
  • βœ… No internal IP exposure in documentation

Documentation Quality βœ…

  • βœ… Realistic API examples for all endpoints
  • βœ… Proper operation summaries and descriptions
  • βœ… Request/response schema documentation
  • βœ… Server URL configured for external access

Testing Integration βœ…

  • βœ… Swagger UI interactive testing enabled
  • βœ… Postman collection export capability
  • βœ… Environment variables configuration
  • βœ… Automated testing workflow setup

πŸš€ Production Benefits Achieved

Benefit Implementation Impact
Centralized Documentation Gateway-aggregated Swagger UI Single source of truth for all APIs
Interactive Testing Swagger UI with realistic examples Immediate API validation without tools
Developer Onboarding Self-documenting APIs with examples Faster integration for new developers
Automated Testing Postman integration workflow CI/CD pipeline API testing
API Consistency Standardized documentation patterns Uniform API design across services

πŸ”— Key Takeaways

  1. Centralized Configuration – Use Spring Cloud Config for consistent SpringDoc settings across all microservices
  2. Gateway Aggregation – Centralize all API documentation through the gateway for unified access
  3. Security Integration – Properly configure security to allow documentation access without compromising API security
  4. Realistic Examples – Include comprehensive API examples to enable immediate testing and understanding
  5. Testing Workflow – Establish clear paths from documentation to automated testing via Postman integration

This implementation transforms your microservice APIs from undocumented backend services into well-documented, easily testable, and professionally presented APIs that developers can immediately understand and integrate with.


πŸš€ Continue Your Documentation Journey

🧭 Next Steps in Spring Documentation:

Part of the AdventureTube technical blog series supporting the JavaiOS YouTube channel.

Leave a Comment

Your email address will not be published. Required fields are marked *