Generated documentation guide (code-first approach)
This guide teaches you how to work with automatically generated OpenAPI documentation using SpringDoc annotations in Java code. You’ll learn to understand, enhance, and validate documentation that stays synchronized with the API implementation.
Duration: 45-60 minutes Prerequisites: Basic understanding of REST APIs and Java annotations
Overview: how generated documentation works
The Customer Management API uses SpringDoc to automatically generate OpenAPI specifications from Java annotations. Here’s how it works:
Java Code + Annotations → SpringDoc → OpenAPI Spec → Swagger UI
↓ ↓ ↓ ↓
Controllers Live Docs JSON/YAML Interactive Testing
Key Benefits:
- Documentation stays synchronized with code changes
- Developers maintain docs while coding
- Reduces documentation drift
- Immediate validation during development
Key Challenges:
- Limited formatting control
- Requires developer cooperation
- Technical writer input needed for quality
Step 1: understanding current annotations
Let’s examine how the existing code creates documentation through annotations.
Before diving into the code, start by running the application and accessing the generated documentation:
# Start the API
./mvnw spring-boot:run
# View interactive documentation
open http://localhost:8080/swagger-ui/index.html
# View raw OpenAPI specification
curl http://localhost:8080/v3/api-docs.yaml
Examine annotation structure
The controller uses several types of annotations to create comprehensive documentation:
1. @Operation annotation
This provides the main description for each endpoint:
@Operation(
summary = "Create a new customer",
description = """
Creates a new customer with complete profile information including nested address data.
This endpoint demonstrates:
- Nested object handling (Address within Customer)
- Enum validation (CustomerType)
- Input validation and error handling
- Database persistence with JPA
""",
tags = {"Single customer CRUD operations"}
)
What this creates:
- Summary: Short description shown in endpoint lists
- Description: Detailed explanation with formatting support
- Tags: Groups endpoints in Swagger UI sections
2. @ApiResponses annotation
This documents all possible response scenarios:
@ApiResponses({
@ApiResponse(
responseCode = "200",
description = "Customer created successfully",
content = @Content(
mediaType = "text/plain",
examples = @ExampleObject(value = "Customer added successfully")
)
),
@ApiResponse(
responseCode = "400",
description = "Invalid customer data provided"
),
@ApiResponse(
responseCode = "409",
description = "Customer with this ID already exists"
)
})
What this creates:
- Complete HTTP status code documentation
- Response format specifications
- Example response content
- Error condition explanations
3. @Parameter annotation
This documents request parameters and body content:
@Parameter(
description = "Customer object with all required fields including nested address",
required = true,
example = """
{
"id": "CUST001",
"name": "Alice Johnson",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zipCode": "10001",
"country": "USA"
},
"phone": "555-0123",
"type": "VIP"
}
"""
)
What this creates:
- Parameter descriptions and requirements
- Request body examples
- Input validation documentation
Step 2: exploring the generated specification
Now that you understand how annotations create documentation, let’s explore what the system actually generates.
Open http://localhost:8080/swagger-ui/index.html and explore:
- API Information Section
- Title: “Customer Management APIs”
- Version: “1.0.0”
- Description and contact information
- Endpoint Groupings (Tags)
- “Single customer CRUD operations”
- “Multiple customer operations”
- Notice how @Tag annotations organize endpoints
- Individual Endpoints
- Click on any endpoint to expand
- Review summary, description, parameters
- Try the “Try it out” functionality
Test documentation accuracy
Verify that the generated documentation matches actual API behavior:
- Test a Simple Request
# Create a customer using the exact example from documentation curl -X POST http://localhost:8080/customer \ -H "Content-Type: application/json" \ -d '{ "id": "CUST001", "name": "Alice Johnson", "address": { "street": "123 Main St", "city": "New York", "state": "NY", "zipCode": "10001", "country": "USA" }, "phone": "555-0123", "type": "VIP" }' - Verify Response Format
- Does the response match the documented examples?
- Are error messages accurate?
- Do status codes align with documentation?
- Test Edge Cases
# Test duplicate ID (should return 409) curl -X POST http://localhost:8080/customer \ -H "Content-Type: application/json" \ -d '{"id": "CUST001", "name": "Test Duplicate"}'
Step 3: accessing raw OpenAPI specification
Understanding the raw specification helps you see exactly what SpringDoc generates from your annotations.
# Get YAML format (more readable)
curl http://localhost:8080/v3/api-docs.yaml > current-api-spec.yaml
# Get JSON format (for tools that prefer JSON)
curl http://localhost:8080/v3/api-docs > current-api-spec.json
Open current-api-spec.yaml and examine:
- OpenAPI Metadata
openapi: 3.0.1 info: title: Customer Management APIs description: REST API with H2 database integration version: 1.0.0 - Generated Schemas
- Customer model schema
- Address embedded schema
- CustomerType enum values
- Error response formats
- Path Definitions
- All endpoints with complete parameter documentation
- Request/response body schemas
- Example values from annotations
Compare with manual specifications
Compare the generated spec with the manual examples in api-assets/openapi/examples/:
# Compare structure and completeness
diff current-api-spec.yaml api-assets/openapi/examples/practice-exercise.yaml
Key Differences to Notice:
- Generated specs include all model properties automatically
- Manual specs allow custom organization and additional metadata
- Generated examples come from code annotations
- Manual specs can include business context not in code
Step 4: enhancing generated documentation
While automatically generated documentation provides a solid foundation, it often needs enhancement to fully serve user needs.
Review the current documentation for areas that could be improved:
- Missing Business Context
- What business rules aren’t documented?
- Are there workflow explanations missing?
- Do error messages provide enough guidance?
- Example Quality
- Are examples realistic and helpful?
- Do they cover common use cases?
- Are error examples included?
- Organization and Grouping
- Are endpoints logically grouped with tags?
- Is the progression intuitive for new users?
- Are related operations near each other?
Working with developers on enhancements
Since you can’t directly edit the generated documentation, improvements require collaboration:
Enhancement Process:
- Document specific improvements needed
- Provide exact text for developers to add
- Test changes after implementation
- Verify accuracy of enhanced documentation
Example Enhancement Request:
Endpoint: POST /customer
Current: "Creates a new customer with complete profile information"
Suggested: "Creates a new customer with complete profile information.
Customer IDs must be unique and follow the format CUSTXXX.
All customers start with INDIVIDUAL type unless specified."
Add to @Operation description:
- ID format requirements: CUSTXXX pattern
- Default type behavior
- Required vs optional fields explanation
Step 5: validation and quality assurance
Even with automatic generation, systematic validation ensures your documentation meets user needs and maintains accuracy.
The generated specification is automatically validated by SpringDoc, but you should verify:
- OpenAPI Compliance
# Use online validator curl -X POST https://validator.swagger.io/validator/validate \ -H "Content-Type: application/json" \ -d @current-api-spec.json - Example Accuracy
- Test every example in the documentation
- Verify all documented status codes are possible
- Check that required/optional field markings are correct
Documentation quality checklist
Use this checklist to evaluate generated documentation quality:
Completeness:
- All endpoints documented
- All parameters described
- All response codes covered
- Examples provided for requests and responses
- Error scenarios documented
Clarity:
- Summaries are concise and descriptive
- Descriptions explain purpose and business context
- Examples use realistic, helpful data
- Error messages guide users to solutions
- Field requirements are clear
Accuracy:
- Examples work when tested
- Status codes match actual API behavior
- Parameter requirements match implementation
- Response formats match actual outputs
- Business rules are correctly documented
Testing integration
Ensure the documentation integrates well with testing tools:
- Swagger UI Testing
- All “Try it out” functions work correctly
- Authentication (if required) is properly configured
- Examples can be executed successfully
- Import to External Tools
# Test Postman import # Import current-api-spec.json into Postman # Verify all requests are properly configured # Test other tools as needed
Step 6: maintenance workflow
Establishing ongoing maintenance processes ensures your documentation remains accurate and valuable as the API evolves.
Set up processes to ensure documentation stays accurate:
- After Code Changes
# Always regenerate and test after API changes ./mvnw clean spring-boot:run curl http://localhost:8080/v3/api-docs.yaml > updated-spec.yaml # Compare with previous version diff current-api-spec.yaml updated-spec.yaml - Before Releases
- Export current specification
- Test all examples in documentation
- Verify new features are properly documented
- Update any external documentation that references the API
Version control integration
Track documentation changes alongside code:
# Save specification snapshots
mkdir -p docs/api-versions
curl http://localhost:8080/v3/api-docs.yaml > docs/api-versions/v$(date +%Y%m%d)-api-spec.yaml
# Compare versions
git diff docs/api-versions/
Key takeaways
Advantages of generated documentation
- Always in sync: Documentation automatically updates with code changes
- Developer ownership: Developers maintain docs while coding
- Immediate validation: Errors caught during development
- Comprehensive coverage: All endpoints automatically included
Technical writer’s role
- Quality assurance: Ensure annotations create clear, helpful documentation
- Enhancement guidance: Identify areas needing improvement and provide specific suggestions
- Testing and validation: Verify documentation accuracy through systematic testing
- User experience: Ensure documentation serves user needs, not just technical requirements
When to use this approach
Best For:
- APIs maintained by active development teams
- Projects where documentation drift is a concern
- Technical audiences comfortable with generated documentation
- Rapid development cycles
Consider Alternatives When:
- Documentation needs extensive custom formatting
- Business context requires non-technical explanations
- API design needs to be documented before implementation
- Marketing or sales materials need to be derived from documentation
Next steps
- Continue learning: Try the Manual YAML writing guide to understand the design-first approach
- Validate your work: Use the Testing and validation guide to systematically verify documentation quality
- Reference materials: Check the Annotation reference for comprehensive SpringDoc annotation documentation
This guide focused on understanding and enhancing automatically generated OpenAPI documentation. The generated approach ensures accuracy and reduces maintenance overhead, making it ideal for technically-oriented teams and rapid development cycles.