self-serve-integration-service
Version:
Self-Serve Integration Service for managing multiple funder integrations including REST APIs, SOAP APIs, and UI automation
456 lines (386 loc) • 11.3 kB
Markdown
# Swagger API Documentation
## Overview
The Self-Serve Integration Service includes comprehensive Swagger/OpenAPI documentation that provides interactive API exploration, testing capabilities, and detailed schema definitions.
## Accessing Swagger Documentation
### Swagger UI
- **URL**: `http://localhost:3003/api-docs`
- **Description**: Interactive web interface for exploring and testing the API
- **Features**:
- Try out API endpoints directly from the browser
- View request/response schemas
- Test with different parameters
- Download API client code
### Swagger JSON
- **URL**: `http://localhost:3003/api-docs.json`
- **Description**: Raw OpenAPI 3.0 specification in JSON format
- **Use Cases**:
- Generate client SDKs
- Import into API testing tools (Postman, Insomnia)
- Integration with CI/CD pipelines
## API Documentation Structure
### Tags and Organization
The API documentation is organized into the following tags:
#### 1. **Integration API**
Main API endpoints for quote and proposal generation across multiple funders.
**Endpoints:**
- `POST /api/integration/quotes/calculate` - Calculate vehicle finance quotes
- `GET /api/integration/quotes/{quoteId}/status` - Get quote status
- `POST /api/integration/proposals/generate` - Generate proposals
- `GET /api/integration/proposals/{proposalId}/status` - Get proposal status
- `GET /api/integration/funders` - List available funders
- `POST /api/integration/funders/{funderName}/test` - Test funder connection
- `GET /api/integration/customers/{email}/quotes` - Get customer quotes
- `GET /api/integration/customers/{email}/proposals` - Get customer proposals
#### 2. **Health Check**
Service health and monitoring endpoints.
**Endpoints:**
- `GET /api/health` - Comprehensive health check
- `GET /api/health/ready` - Readiness check
- `GET /api/health/live` - Liveness check
### Schema Definitions
#### Core Data Models
**CustomerDetails**
```json
{
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phone": "+44 7700 900001",
"dateOfBirth": "1985-06-20",
"address": {
"line1": "123 Main Street",
"line2": "Apartment 4B",
"city": "London",
"postcode": "SW1A 1AA",
"country": "UK"
},
"employment": {
"employerName": "Tech Solutions Ltd",
"jobTitle": "Software Engineer",
"employmentType": "FULL_TIME",
"monthlyIncome": 4500
},
"financial": {
"annualIncome": 54000,
"creditScore": "EXCELLENT"
}
}
```
**VehicleDetails**
```json
{
"make": "BMW",
"model": "3 Series",
"variant": "320d M Sport",
"year": 2024,
"price": 38000,
"mileage": 0,
"fuelType": "DIESEL",
"transmission": "AUTOMATIC",
"bodyType": "SALOON",
"doors": 4,
"seats": 5,
"engineSize": "2.0L",
"power": 190,
"co2Emissions": 145,
"registration": "AB12 CDE",
"vin": "WBAFR7C50BC123456",
"capId": "12345",
"capCode": "BMW320DMS",
"color": "Alpine White",
"options": ["Navigation", "Leather Seats", "Sunroof"],
"accessories": [
{
"type": "DealerFit",
"description": "Premium Sound System",
"price": 1500.00
}
]
}
```
**ContractDetails**
```json
{
"quoteType": "PERSONAL_CONTRACT_HIRE",
"term": 36,
"deposit": 2500,
"annualMileage": 12000,
"reliefVehicle": false,
"estimatedSalesValue": 15000,
"customerReference": "CUST-2024-001",
"estimatedDeliveryDate": "2024-12-01",
"adjustments": {
"offInvoiceSupport": 1000,
"otrp": 38000,
"commission": 500,
"discount": 2000,
"customerTerms": 0,
"co2Emission": 145
}
}
```
#### Request/Response Models
**CommonQuoteRequest**
```json
{
"funderName": "LEX",
"environment": "SANDBOX",
"customerDetails": { /* CustomerDetails */ },
"vehicleDetails": { /* VehicleDetails */ },
"contractDetails": { /* ContractDetails */ },
"source": "SELF_SERVE_APP",
"correlationId": "req-123456789"
}
```
**CommonQuoteResponse**
```json
{
"id": "123e4567-e89b-12d3-a456-426614174000",
"funderName": "LEX",
"externalQuoteId": "Q12345",
"externalReference": "LEX-2024-001",
"monthlyPayment": 450.00,
"totalAmount": 16200.00,
"apr": 4.9,
"interestRate": 4.5,
"balloonPayment": 8000.00,
"validUntil": "2024-12-31T23:59:59Z",
"status": "GENERATED",
"createdAt": "2024-08-26T10:20:54.000Z",
"funderResponseData": { /* Raw funder response */ }
}
```
### Error Handling
All endpoints return consistent error responses:
**Error Response Format**
```json
{
"success": false,
"error": "Validation failed",
"details": [
{
"field": "customerDetails.email",
"message": "Valid email is required"
}
]
}
```
**HTTP Status Codes**
- `200` - Success
- `400` - Bad Request (validation errors)
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `500` - Internal Server Error
- `503` - Service Unavailable (health checks)
## Testing with Swagger UI
### 1. **Quote Calculation Example**
1. Navigate to `POST /api/integration/quotes/calculate`
2. Click "Try it out"
3. Use the provided example or modify the request body
4. Click "Execute"
5. Review the response and status code
**Sample Request:**
```json
{
"funderName": "LEX",
"environment": "SANDBOX",
"customerDetails": {
"firstName": "John",
"lastName": "Doe",
"email": "john.doe@example.com",
"phone": "+447700900000",
"dateOfBirth": "1980-01-01",
"address": {
"line1": "123 Main St",
"city": "London",
"postcode": "SW1A 0AA",
"country": "UK"
},
"employment": {
"employerName": "Acme Corp",
"jobTitle": "Engineer",
"employmentType": "FULL_TIME",
"monthlyIncome": 3000
}
},
"vehicleDetails": {
"make": "Kia",
"model": "Sportage",
"year": 2025,
"price": 25000,
"mileage": 100,
"fuelType": "Petrol",
"transmission": "Automatic",
"capId": "105841",
"capCode": "KISP16SHD5EHTA 6"
},
"contractDetails": {
"quoteType": "BUSINESS_CONTRACT_HIRE",
"term": 36,
"deposit": 2000,
"annualMileage": 10000,
"reliefVehicle": false,
"adjustments": {
"otrp": 25000,
"co2Emission": 145
}
},
"source": "SELF_SERVE_APP",
"correlationId": "req-123456789"
}
```
### 2. **Health Check Example**
1. Navigate to `GET /api/health`
2. Click "Try it out"
3. Click "Execute"
4. Review the health status of all funders
### 3. **Funder Testing Example**
1. Navigate to `POST /api/integration/funders/LEX/test`
2. Click "Try it out"
3. Use request body:
```json
{
"environment": "SANDBOX"
}
```
4. Click "Execute"
5. Review the connection test results
## API Client Generation
### Using Swagger Codegen
1. **Download the OpenAPI spec:**
```bash
curl -o api-spec.json http://localhost:3003/api-docs.json
```
2. **Generate client code:**
```bash
# JavaScript/TypeScript
npx @openapitools/openapi-generator-cli generate \
-i api-spec.json \
-g typescript-axios \
-o ./client
# Python
npx @openapitools/openapi-generator-cli generate \
-i api-spec.json \
-g python \
-o ./python-client
# Java
npx @openapitools/openapi-generator-cli generate \
-i api-spec.json \
-g java \
-o ./java-client
```
### Using Postman
1. Import the OpenAPI spec into Postman
2. Generate a collection automatically
3. Test all endpoints with different parameters
## Development and Customization
### Adding New Endpoints
1. **Add Swagger documentation to your route:**
```typescript
/**
* @swagger
* /api/integration/new-endpoint:
* post:
* summary: New endpoint description
* description: Detailed description of the endpoint
* tags: [Integration API]
* requestBody:
* required: true
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/YourSchema'
* responses:
* 200:
* description: Success response
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/YourResponseSchema'
*/
```
2. **Add new schemas to swagger.ts:**
```typescript
YourSchema: {
type: 'object',
properties: {
// Define your schema properties
}
}
```
### Customizing Swagger UI
Modify the Swagger setup in `src/config/swagger.ts`:
```typescript
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs, {
explorer: true,
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'Your Custom Title',
swaggerOptions: {
persistAuthorization: true,
displayRequestDuration: true,
filter: true,
showExtensions: true,
showCommonExtensions: true
}
}));
```
## Best Practices
### 1. **Documentation Standards**
- Always include comprehensive descriptions
- Provide realistic examples
- Use proper HTTP status codes
- Include validation rules in descriptions
### 2. **Schema Design**
- Use descriptive property names
- Include format specifications (email, date, uuid)
- Provide examples for all properties
- Use enums for limited value sets
### 3. **Error Handling**
- Document all possible error responses
- Use consistent error response format
- Include detailed validation error messages
### 4. **Testing**
- Test all endpoints through Swagger UI
- Verify request/response schemas
- Test error scenarios
- Validate authentication flows
## Troubleshooting
### Common Issues
1. **Swagger UI not loading:**
- Check if the service is running on the correct port
- Verify the `/api-docs` route is accessible
- Check browser console for JavaScript errors
2. **Schema validation errors:**
- Ensure all required properties are marked correctly
- Check for typos in schema references
- Verify enum values match actual implementation
3. **Missing endpoints:**
- Ensure routes are properly imported in `index.ts`
- Check that Swagger documentation is correctly formatted
- Verify the `apis` array in swagger config includes your route files
### Debug Mode
Enable debug logging by setting:
```bash
LOG_LEVEL=debug
```
This will provide detailed information about Swagger processing and API calls.
## Integration with CI/CD
### Automated Testing
Use the OpenAPI spec for automated API testing:
```yaml
# GitHub Actions example
- name: Test API with OpenAPI spec
run: |
npm install -g newman
newman run api-tests.postman_collection.json \
--environment api-tests.postman_environment.json
```
### API Contract Testing
Ensure API changes don't break existing contracts:
```bash
# Using swagger-diff
npx swagger-diff api-spec-v1.json api-spec-v2.json
```
---
**For more information, visit the [Swagger UI](http://localhost:3003/api-docs) or download the [OpenAPI specification](http://localhost:3003/api-docs.json).**