Files
dbis_core/docs/api-guide.md

515 lines
12 KiB
Markdown
Raw Normal View History

2025-12-12 15:02:56 -08:00
# DBIS Core Banking System - API Documentation Guide
This guide provides comprehensive API documentation standards, best practices, and examples for the DBIS Core Banking System.
## API Architecture
```mermaid
graph TB
subgraph "Client Layer"
WEB[Web Clients]
MOBILE[Mobile Apps]
PARTNER[Partner Systems]
INTERNAL[Internal Services]
end
subgraph "API Gateway"
GATEWAY[API Gateway]
AUTH[Authentication]
RATE[Rate Limiting]
ROUTING[Request Routing]
end
subgraph "Service Layer"
PAYMENT[Payment Service]
FX[FX Service]
CBDC[CBDC Service]
LEDGER[Ledger Service]
end
subgraph "Data Layer"
DB[(Database)]
CACHE[(Cache)]
HSM[HSM]
end
WEB --> GATEWAY
MOBILE --> GATEWAY
PARTNER --> GATEWAY
INTERNAL --> GATEWAY
GATEWAY --> AUTH
AUTH --> RATE
RATE --> ROUTING
ROUTING --> PAYMENT
ROUTING --> FX
ROUTING --> CBDC
ROUTING --> LEDGER
PAYMENT --> DB
FX --> DB
CBDC --> DB
LEDGER --> DB
PAYMENT --> CACHE
FX --> CACHE
CBDC --> CACHE
PAYMENT --> HSM
FX --> HSM
CBDC --> HSM
LEDGER --> HSM
```
## API Request Flow
```mermaid
sequenceDiagram
participant Client
participant Gateway as API Gateway
participant Auth as Auth Service
participant Service as Business Service
participant DB as Database
participant HSM
Client->>Gateway: HTTP Request
Gateway->>Gateway: Validate Request Format
Gateway->>Auth: Authenticate Request
Auth->>HSM: Verify Signature
HSM-->>Auth: Signature Valid
Auth->>Auth: Check Permissions
Auth-->>Gateway: Authorized
Gateway->>Gateway: Apply Rate Limiting
Gateway->>Service: Route Request
Service->>DB: Query Data
DB-->>Service: Return Data
Service->>Service: Process Business Logic
Service-->>Gateway: Response
Gateway-->>Client: HTTP Response
```
## API Design Principles
### RESTful Design
1. **Resource-Based URLs**
- Use nouns, not verbs
- Use plural nouns for collections
- Use hierarchical structure
2. **HTTP Methods**
- GET: Retrieve resources
- POST: Create resources
- PUT: Update resources (full)
- PATCH: Update resources (partial)
- DELETE: Delete resources
3. **Status Codes**
- 200: Success
- 201: Created
- 400: Bad Request
- 401: Unauthorized
- 403: Forbidden
- 404: Not Found
- 500: Internal Server Error
### Request/Response Format
#### Request Headers
```http
Authorization: Bearer <jwt_token>
Content-Type: application/json
X-Request-ID: <correlation_id>
X-Signature: <request_signature>
X-Timestamp: <unix_timestamp>
```
#### Response Format
```json
{
"success": true,
"data": {
// Response data
},
"metadata": {
"requestId": "req_123",
"timestamp": "2024-01-15T10:30:00Z",
"version": "1.0"
}
}
```
#### Error Response Format
```json
{
"success": false,
"error": {
"code": "INSUFFICIENT_BALANCE",
"message": "Insufficient balance in source account",
"details": {
"accountId": "acc_123",
"availableBalance": 100.00,
"requestedAmount": 200.00
}
},
"metadata": {
"requestId": "req_123",
"timestamp": "2024-01-15T10:30:00Z"
}
}
```
## Authentication & Authorization
### Authentication Flow
```mermaid
sequenceDiagram
participant Client
participant API as API Gateway
participant Auth as Auth Service
participant HSM
Client->>API: Request with Credentials
API->>Auth: Validate Credentials
Auth->>HSM: Generate/Verify Token
HSM-->>Auth: Token
Auth-->>API: JWT Token
API-->>Client: Return JWT Token
Client->>API: Request with JWT Token
API->>Auth: Validate JWT
Auth->>HSM: Verify Signature
HSM-->>Auth: Valid
Auth-->>API: Authorized
API->>API: Process Request
```
### Authorization
1. **Role-Based Access Control (RBAC)**
- Define roles (admin, operator, viewer)
- Assign permissions to roles
- Check permissions on each request
2. **Resource-Based Authorization**
- Check ownership
- Verify access rights
- Validate business rules
## Rate Limiting
### Rate Limiting Strategy
```mermaid
graph TD
subgraph "Rate Limiting Tiers"
TIER1[Tier 1: Critical Endpoints<br/>100 req/min]
TIER2[Tier 2: Standard Endpoints<br/>1000 req/min]
TIER3[Tier 3: Read-Only Endpoints<br/>10000 req/min]
end
TIER1 --> ENFORCE[Rate Limiter]
TIER2 --> ENFORCE
TIER3 --> ENFORCE
ENFORCE --> ALLOW[Allow Request]
ENFORCE --> REJECT[Reject Request<br/>429 Too Many Requests]
```
### Rate Limit Headers
```http
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 950
X-RateLimit-Reset: 1642248000
```
## API Versioning
### Versioning Strategy
```mermaid
graph LR
subgraph "Versioning Approaches"
URL[URL Versioning<br/>/api/v1/payments]
HEADER[Header Versioning<br/>Accept: application/vnd.dbis.v1+json]
QUERY[Query Versioning<br/>?version=1]
end
URL --> RECOMMENDED[Recommended]
HEADER --> ALTERNATIVE[Alternative]
QUERY --> NOT_RECOMMENDED[Not Recommended]
```
### Version Lifecycle
1. **Current Version**: Actively maintained
2. **Deprecated Version**: Still supported, migration recommended
3. **Retired Version**: No longer supported
## Error Handling
### Error Categories
```mermaid
graph TD
subgraph "Error Types"
CLIENT[Client Errors<br/>4xx]
SERVER[Server Errors<br/>5xx]
BUSINESS[Business Logic Errors]
end
CLIENT --> VALIDATION[Validation Errors]
CLIENT --> AUTH[Authentication Errors]
CLIENT --> PERM[Permission Errors]
SERVER --> INTERNAL[Internal Server Errors]
SERVER --> TIMEOUT[Timeout Errors]
SERVER --> UNAVAILABLE[Service Unavailable]
BUSINESS --> INSUFFICIENT[Insufficient Balance]
BUSINESS --> INVALID[Invalid State]
BUSINESS --> CONFLICT[Business Rule Conflicts]
```
### Error Response Codes
| Code | Category | Description |
|------|----------|-------------|
| 400 | Client Error | Bad Request |
| 401 | Client Error | Unauthorized |
| 403 | Client Error | Forbidden |
| 404 | Client Error | Not Found |
| 409 | Client Error | Conflict |
| 429 | Client Error | Too Many Requests |
| 500 | Server Error | Internal Server Error |
| 503 | Server Error | Service Unavailable |
## API Documentation Standards
### OpenAPI/Swagger Specification
All APIs should be documented using OpenAPI 3.0 specification:
```yaml
openapi: 3.0.0
info:
title: DBIS Core Banking API
version: 1.0.0
description: Sovereign-grade financial infrastructure API
paths:
/api/v1/payments:
post:
summary: Create a payment
requestBody:
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/PaymentRequest'
responses:
'201':
description: Payment created
content:
application/json:
schema:
$ref: '#/components/schemas/PaymentResponse'
'400':
description: Bad request
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
```
### Documentation Requirements
1. **Endpoint Documentation**
- Description
- Request/response schemas
- Example requests/responses
- Error responses
- Authentication requirements
2. **Schema Documentation**
- Field descriptions
- Data types
- Validation rules
- Example values
3. **Authentication Documentation**
- Authentication methods
- Token generation
- Token usage
- Permission requirements
## Best Practices
### API Design
1. **Consistency**
- Use consistent naming conventions
- Follow RESTful principles
- Standardize error responses
2. **Idempotency**
- Use idempotency keys
- Support idempotent operations
- Return same response for duplicate requests
3. **Pagination**
- Use cursor-based pagination
- Limit page size
- Provide pagination metadata
4. **Filtering & Sorting**
- Support filtering by common fields
- Enable sorting by relevant fields
- Document filter/sort options
### Security
1. **Input Validation**
- Validate all inputs
- Use schema validation
- Sanitize user inputs
2. **Output Sanitization**
- Don't expose sensitive data
- Mask sensitive fields
- Use appropriate content types
3. **HTTPS Only**
- Enforce HTTPS
- Use TLS 1.3
- Implement HSTS
### Performance
1. **Caching**
- Cache GET requests
- Use appropriate cache headers
- Implement cache invalidation
2. **Compression**
- Use gzip compression
- Compress large responses
- Support content negotiation
3. **Async Operations**
- Use async for long operations
- Provide status endpoints
- Support webhooks
## API Testing
### Testing Strategy
```mermaid
graph TD
subgraph "API Testing"
UNIT[Unit Tests]
INT[Integration Tests]
E2E[E2E Tests]
LOAD[Load Tests]
SEC[Security Tests]
end
UNIT --> COVERAGE[Test Coverage]
INT --> COVERAGE
E2E --> COVERAGE
LOAD --> PERFORMANCE[Performance Validation]
SEC --> SECURITY[Security Validation]
```
### Test Examples
1. **Happy Path Tests**
- Valid requests
- Successful responses
- Expected behavior
2. **Error Scenarios**
- Invalid inputs
- Authentication failures
- Business rule violations
3. **Edge Cases**
- Boundary values
- Null/empty inputs
- Concurrent requests
## Recommendations
### Priority: High
1. **API Documentation**
- Document all endpoints
- Keep documentation up to date
- Provide interactive examples
2. **Versioning Strategy**
- Implement URL versioning
- Maintain backward compatibility
- Plan deprecation timelines
3. **Error Handling**
- Standardize error responses
- Provide meaningful error messages
- Include error codes
4. **Rate Limiting**
- Implement per-endpoint limits
- Use sliding window algorithm
- Provide rate limit headers
For detailed recommendations, see [RECOMMENDATIONS.md](./RECOMMENDATIONS.md).
## Exchange Integrations
### Crypto.com OTC 2.0 API
The DBIS Core includes integration with the [Crypto.com Exchange OTC 2.0 REST/WebSocket API](https://exchange-docs.crypto.com/exchange/v1/rest-ws/index_OTC2.html) for institutional OTC trading.
**Module Location:** `src/core/exchange/crypto-com-otc/`
**API Base Path:** `/api/v1/crypto-com-otc`
**Features:**
- Request-for-Quote (RFQ) via WebSocket
- Deal execution
- FX price provider integration (FxService.getMarketPrice uses OTC when available)
- Settle-later limit and unsettled amount tracking
- Deal persistence to `otc_trades` table
- Rate limiting (1 req/s REST, 2 req/s WebSocket)
- Retry with exponential backoff
**Environment Variables:** `CRYPTO_COM_API_KEY`, `CRYPTO_COM_API_SECRET`, `CRYPTO_COM_ENVIRONMENT` (optional)
**Documentation:** [Crypto.com OTC Module README](../src/core/exchange/crypto-com-otc/README.md) | [DBIS Core API Reference](../../docs/11-references/DBIS_CORE_API_REFERENCE.md)
### Exchange Registry API
**Base Path:** `/api/v1/exchange`
Multi-exchange price aggregation with fallback. Providers: Binance, Kraken (public), Oanda, FXCM (optional API keys).
**Endpoints:** `GET /price?pair=BTC/USD`, `GET /providers`
**Location:** `src/core/exchange/exchange-registry.service.ts`, `exchange.routes.ts`
2025-12-12 15:02:56 -08:00
---
## Related Documentation
- [Best Practices Guide](./BEST_PRACTICES.md)
- [Recommendations](./RECOMMENDATIONS.md)
- [Development Guide](./development.md)
- [Architecture Atlas](./architecture-atlas.md)