### 1.1 OpenAPI-Dokumentation implementieren - Swagger/OpenAPI in bestehenden Ktor-Diensten integrieren - Zentrale API-Dokumentationsseite im API-Gateway erstellen - CI/CD-Pipeline um automatische API-Dokumentationsgenerierung erweitern - Entwickler-Guidelines für API-Dokumentation erstellen
10 KiB
API Documentation - Meldestelle Self-Contained Systems
Overview
This document provides comprehensive documentation for the Meldestelle API Gateway, which aggregates all bounded context APIs into a unified interface while maintaining the independence of each context.
Features Implemented
✅ OpenAPI/Swagger Integration
- OpenAPI 3.0 specification using static YAML file
- Swagger UI interactive documentation
- Comprehensive API documentation for all bounded contexts
- Multiple server environments (development, staging, production)
✅ Postman Collections
- Comprehensive API collection covering all endpoints
- Environment variables for easy configuration
- Authentication token management with automatic token extraction
- Pre-configured request examples for all endpoints
✅ API Tests
- Integration tests for all major endpoints
- Authentication flow testing
- CRUD operation validation
- Error handling verification
API Structure
The API Gateway aggregates the following bounded contexts:
1. System Information
GET /- API Gateway informationGET /health- Health check for all contextsGET /docs- Central API documentation pageGET /api- Redirects to central API documentation pageGET /api/json- API documentation overview in JSON formatGET /swagger- Interactive Swagger UIGET /openapi- Raw OpenAPI specification
2. Authentication Context (/auth/*)
POST /auth/register- User registrationPOST /auth/login- User authenticationGET /auth/profile- Get user profilePUT /auth/profile- Update user profilePOST /auth/change-password- Change password
3. Master Data Context (/api/masterdata/*)
GET /api/masterdata/countries- Get all countriesGET /api/masterdata/countries/active- Get active countriesGET /api/masterdata/countries/{id}- Get country by IDGET /api/masterdata/countries/iso/{code}- Get country by ISO codePOST /api/masterdata/countries- Create countryPUT /api/masterdata/countries/{id}- Update countryDELETE /api/masterdata/countries/{id}- Delete country
4. Horse Registry Context (/api/horses/*)
GET /api/horses- Get all horsesGET /api/horses/active- Get active horsesGET /api/horses/{id}- Get horse by IDGET /api/horses/search- Search horses by nameGET /api/horses/owner/{ownerId}- Get horses by ownerPOST /api/horses- Create horsePUT /api/horses/{id}- Update horseDELETE /api/horses/{id}- Delete horseDELETE /api/horses/batch- Batch delete horsesGET /api/horses/stats- Get horse statistics
5. Event Management Context (/api/events/*)
GET /api/events- Get all eventsGET /api/events/stats- Get event statisticsPOST /api/events- Create eventGET /api/events/{id}- Get event by IDPUT /api/events/{id}- Update eventDELETE /api/events/{id}- Delete eventGET /api/events/search- Search eventsGET /api/events/organizer/{organizerId}- Get events by organizer
Getting Started
1. Start the API Gateway
# Navigate to the project root
cd /path/to/meldestelle
# Run the API Gateway
./gradlew :api-gateway:run
The API will be available at http://localhost:8080
2. Access Swagger UI
Open your browser and navigate to:
http://localhost:8080/swagger
This provides an interactive interface to explore and test all API endpoints.
3. Use Postman Collection
- Import the Postman collection from
docs/postman/Meldestelle_API_Collection.json - Set the
baseUrlvariable tohttp://localhost:8080 - Start with the "System Information" folder to verify the API is running
- Use the "Authentication Context" to get an auth token
- The token will be automatically saved and used for authenticated endpoints
Authentication
The API uses JWT (JSON Web Token) based authentication:
- Register a new user via
POST /auth/register - Login with credentials via
POST /auth/login - Extract the JWT token from the login response
- Include the token in the
Authorizationheader:Bearer <token>
Example Authentication Flow
# 1. Register a new user
curl -X POST http://localhost:8080/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "SecurePassword123!",
"firstName": "Test",
"lastName": "User",
"phoneNumber": "+43123456789"
}'
# 2. Login to get token
curl -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "test@example.com",
"password": "SecurePassword123!"
}'
# 3. Use token for authenticated requests
curl -X GET http://localhost:8080/api/horses \
-H "Authorization: Bearer <your-jwt-token>"
Response Format
All API responses follow a consistent format using the BaseDto wrapper:
{
"success": true,
"data": {
"example": "Actual response data goes here"
},
"message": "Operation completed successfully",
"timestamp": "2024-01-15T10:30:00Z"
}
Error Response Format
{
"success": false,
"data": null,
"message": "Error description",
"errors": [
{
"field": "email",
"message": "Invalid email format"
}
],
"timestamp": "2024-01-15T10:30:00Z"
}
Testing
Running API Tests
# Run all API Gateway tests
./gradlew :api-gateway:test
# Run specific test class
./gradlew :api-gateway:test --tests "ApiIntegrationTest"
# Run with verbose output
./gradlew :api-gateway:test --info
Test Coverage
The test suite covers:
- ✅ API Gateway information endpoints
- ✅ Health check functionality
- ✅ OpenAPI/Swagger integration
- ✅ Authentication endpoints structure
- ✅ Master data CRUD operations
- ✅ Horse registry endpoints
- ✅ Error handling and validation
- ✅ CORS configuration
- ✅ Content negotiation
Development
Adding New Endpoints
- Create the endpoint in the appropriate controller
- Add route configuration in
RoutingConfig.kt - Update Postman collection with new requests
- Add integration tests for the new functionality
- Update this documentation
OpenAPI Documentation
The API documentation is maintained in a static OpenAPI YAML file:
# Location: api-gateway/src/jvmMain/resources/openapi/documentation.yaml
paths:
/api/horses:
get:
tags:
- Horse Registry
summary: Get All Horses
description: Returns a list of all horses
operationId: getAllHorses
security:
- bearerAuth: []
responses:
'200':
description: Successful operation
content:
application/json:
schema:
$ref: '#/components/schemas/HorsesResponse'
To update the API documentation:
- Edit the
documentation.yamlfile inapi-gateway/src/jvmMain/resources/openapi/ - Follow the OpenAPI 3.0.3 specification format
- Restart the application to see changes in Swagger UI
Configuration
Environment Variables
| Variable | Description | Default |
|---|---|---|
SERVER_PORT |
API Gateway port | 8080 |
DATABASE_URL |
Database connection URL | jdbc:h2:mem:test |
JWT_SECRET |
JWT signing secret | Generated |
CORS_ORIGINS |
Allowed CORS origins | * |
Application Configuration
The API Gateway can be configured via application.conf:
ktor {
application {
modules = [ at.mocode.gateway.ApplicationKt.module ]
}
deployment {
port = 8080
port = ${?SERVER_PORT}
}
}
database {
url = "jdbc:h2:mem:test"
url = ${?DATABASE_URL}
user = "sa"
password = ""
}
Monitoring and Logging
Health Checks
The /health endpoint provides status information for all bounded contexts:
{
"success": true,
"data": {
"status": "UP",
"contexts": {
"authentication": "UP",
"master-data": "UP",
"horse-registry": "UP"
}
}
}
Logging
The API Gateway uses structured logging with the following levels:
ERROR- System errors and exceptionsWARN- Business logic warningsINFO- Request/response loggingDEBUG- Detailed debugging information
Security
Authentication & Authorization
- JWT-based authentication for stateless security
- Role-based access control (RBAC) for fine-grained permissions
- Password hashing using bcrypt
- Token expiration and refresh mechanisms
CORS Configuration
Cross-Origin Resource Sharing (CORS) is configured to allow:
- Specific origins for production environments
- All HTTP methods (GET, POST, PUT, DELETE, OPTIONS)
- Custom headers including Authorization
Input Validation
All API endpoints implement:
- Request body validation using Kotlin serialization
- Parameter validation for path and query parameters
- Business rule validation in use case layers
- SQL injection prevention through parameterized queries
Troubleshooting
Common Issues
-
Port already in use
# Check what's using port 8080 lsof -i :8080 # Kill the process or use a different port SERVER_PORT=8081 ./gradlew :api-gateway:run -
Database connection issues
# Check database configuration # Verify connection string and credentials # Ensure database server is running -
Authentication failures
# Verify JWT token is valid and not expired # Check Authorization header format: "Bearer <token>" # Ensure user has required permissions
Debug Mode
Enable debug logging for troubleshooting:
# Run with debug logging
./gradlew :api-gateway:run --debug
# Or set log level in application.conf
logger.level = DEBUG
Contributing
When contributing to the API:
- Follow REST conventions for endpoint design
- Maintain backward compatibility when possible
- Update documentation for any API changes
- Add comprehensive tests for new functionality
- Use consistent error handling patterns
Support
For API support and questions:
- Documentation: This file and Swagger UI
- Issues: Create GitHub issues for bugs
- Testing: Use Postman collection for manual testing
- Monitoring: Check
/healthendpoint for system status