# Production API Best Practices

## API Versioning Strategy

### URL Path Versioning
```
/api/v1/investor/dashboard
/api/v2/investor/dashboard (future)
```

**Advantages:**
- Clear version in URL
- Easy to route different versions
- Client can specify version explicitly

**Deprecation Policy:**
- Support old versions for 6 months
- Announce deprecation 3 months in advance
- Add `X-API-Deprecated` header
- Return `410 Gone` after deprecation period

### Version Migration
```php
// routes/api.php
Route::prefix('v1')->group(function () {
    // V1 endpoints
});

Route::prefix('v2')->group(function () {
    // V2 endpoints (future)
});
```

## Mobile-First API Architecture

### Mobile Optimization
1. **Minimize Payload Size**
   - Use pagination (default 20 items)
   - Exclude unnecessary fields
   - Use gzip compression
   - Limit nested relationships

2. **Offline Support**
   - Include timestamps for data freshness
   - Provide sync endpoints
   - Use ETags for conditional requests

3. **Battery Optimization**
   - Reduce polling frequency
   - Use push notifications for updates
   - Batch operations when possible

4. **Network Efficiency**
   - Support HTTP/2
   - Enable keep-alive connections
   - Use connection pooling

### Mobile-Specific Headers
```php
// Add to API responses
$headers = [
    'X-Mobile-App-Version' => $request->header('X-Mobile-App-Version'),
    'X-Device-ID' => $request->header('X-Device-ID'),
    'X-Platform' => $request->header('X-Platform'), // ios/android
];
```

## Finance-Grade API Safety

### Immutable Responses
- Never expose raw model data
- Always use API Resources
- Format financial values as strings
- Never expose internal IDs in client URLs

### Decimal Precision
- All currency values: 2 decimal places
- All percentages: 2 decimal places
- All ratios: 8 decimal places
- All prices: 5 decimal places

### Financial Validation
```php
// Validate financial inputs
$validator = Validator::make($request->all(), [
    'amount' => 'required|numeric|min:0|max:9999999999.99',
    'percentage' => 'required|numeric|min:0|max:100',
]);
```

### Audit Trail
- Log all financial operations
- Include user ID and timestamp
- Store request/response for critical operations
- Use immutable logging (append-only)

## Immutable Response Practices

### No Model Exposure
```php
// BAD - Exposes raw model
return response()->json($investor);

// GOOD - Uses API Resource
return response()->json([
    'success' => true,
    'data' => new InvestorResource($investor),
]);
```

### Consistent Timestamps
- Always use ISO 8601 format
- Use UTC timezone
- Include timezone in response

### No Internal IDs in URLs
```php
// BAD
GET /api/v1/investor/profile/12345

// GOOD - Use authenticated user
GET /api/v1/investor/profile
```

## Pagination Best Practices

### Standard Pagination
```php
$query->paginate($perPage, ['*'], 'page', $page);
```

### Cursor-Based Pagination (for large datasets)
```php
$query->cursorPaginate($perPage);
```

### Pagination Response Format
```json
{
  "data": [ ... ],
  "meta": {
    "current_page": 1,
    "per_page": 20,
    "total": 100,
    "last_page": 5,
    "from": 1,
    "to": 20,
    "has_more_pages": true
  }
}
```

### Pagination Best Practices
- Default page size: 20
- Maximum page size: 100
- Include total count for UI
- Use cursor pagination for infinite scroll

## Caching Recommendations

### HTTP Caching
```php
// Add cache headers
return response()
    ->json($data)
    ->header('Cache-Control', 'public, max-age=300') // 5 minutes
    ->header('ETag', md5(json_encode($data)));
```

### Application-Level Caching
```php
// Cache expensive queries
$investors = Cache::remember('investors.active', 300, function () {
    return Investor::where('is_active', true)->get();
});
```

### Cache Invalidation
- Invalidate on model changes
- Use cache tags for grouped invalidation
- Set appropriate TTL (Time To Live)

### Cache Strategy
- **Dashboard data**: 5 minutes
- **Profile data**: 1 hour
- **Historical data**: 1 day
- **Real-time data**: No cache

## Security Best Practices

### Input Validation
```php
// Validate all inputs
$validator = Validator::make($request->all(), [
    'email' => 'required|email|max:255',
    'amount' => 'required|numeric|min:0',
]);
```

### Output Sanitization
- Never trust client input
- Escape all output
- Use prepared statements (Eloquent handles this)

### Authentication
- Use Sanctum tokens
- Set token expiration (default 1 year)
- Implement token refresh
- Revoke tokens on logout

### Authorization
- Role-based access control (RBAC)
- Resource-based permissions
- Admin-only endpoints protected

### Rate Limiting
- Per-role rate limits
- Per-endpoint rate limits
- IP-based rate limiting
- Distributed rate limiting (Redis)

## Error Handling

### Standardized Error Responses
```json
{
  "success": false,
  "message": "Error description",
  "errors": {
    "field": ["error message"]
  },
  "timestamp": "2026-05-11T12:00:00Z"
}
```

### Error Codes
- `400` - Bad Request
- `401` - Unauthorized
- `403` - Forbidden
- `404` - Not Found
- `422` - Validation Error
- `429` - Too Many Requests
- `500` - Internal Server Error

### Error Logging
- Log all errors with context
- Include user ID and request details
- Use dedicated error channels
- Alert on critical errors

## Performance Optimization

### Database Optimization
- Use eager loading to prevent N+1 queries
- Add indexes on frequently queried columns
- Use query caching
- Optimize slow queries

### Response Optimization
- Minimize payload size
- Use compression (gzip)
- Remove unnecessary fields
- Use pagination

### Connection Pooling
- Configure database connection pool
- Use persistent connections
- Monitor connection count
- Set appropriate timeouts

## Testing Strategy

### Unit Testing
- Test all controller methods
- Test validation rules
- Test business logic
- Mock external dependencies

### Integration Testing
- Test API endpoints end-to-end
- Test authentication flow
- Test authorization rules
- Test error handling

### Load Testing
- Test under concurrent load
- Test rate limiting
- Test database performance
- Test cache effectiveness

### Security Testing
- Test for SQL injection
- Test for XSS
- Test CSRF protection
- Test authentication bypass

## Documentation

### API Documentation
- Use OpenAPI/Swagger
- Document all endpoints
- Include request/response examples
- Document authentication

### Code Documentation
- Document complex business logic
- Document financial calculations
- Document security measures
- Document API contracts

## Deployment Checklist

### Pre-Deployment
- [ ] All tests passing
- [ ] Code reviewed
- [ ] Security audit completed
- [ ] Performance benchmarks met
- [ ] Documentation updated

### Deployment
- [ ] Zero-downtime deployment
- [ ] Database migrations run
- [ ] Cache cleared
- [ ] Monitoring enabled
- [ ] Rollback plan ready

### Post-Deployment
- [ ] Smoke tests passed
- [ ] Monitoring configured
- [ ] Alerts configured
- [ ] Performance verified
- [ ] Error rates monitored

## Monitoring & Observability

### Key Metrics
- API response time (p50, p95, p99)
- Error rate (4xx, 5xx)
- Rate limit hits
- Database query performance
- Cache hit rate
- Concurrent users

### Alerting
- Critical: API error rate > 10%
- Warning: API error rate > 5%
- Critical: Response time p95 > 2s
- Warning: Response time p95 > 1s

### Logging
- All API requests logged
- All errors logged with context
- Performance metrics logged
- Security events logged

## Compliance

### Financial Regulations
- GDPR compliance (data protection)
- Financial audit requirements
- Transaction logging
- Data retention policies

### Security Standards
- OWASP Top 10 compliance
- PCI DSS (if processing payments)
- SOC 2 compliance (if applicable)

## Maintenance

### Regular Tasks
- Review error logs weekly
- Update dependencies monthly
- Security patches immediately
- Performance reviews quarterly
- Architecture reviews annually

### Deprecation Process
1. Announce deprecation (3 months)
2. Add deprecation header
3. Monitor usage
4. Remove endpoint (after 6 months)

## Summary

Following these best practices ensures:
- Scalable API architecture
- Mobile-optimized performance
- Finance-grade security
- Production-ready reliability
- Maintainable codebase
- Compliant operations
