Spaces:
Paused

yaz / src /core /services /api_response.py
anaselamr's picture
fix(collaboration): production-ready collaboration fixes — all 19 engines
0743ddc
Raw History Blame Contribute Delete
12.5 kB
"""
YAZ Care Platform - Standardized API Response Wrapper
State-of-the-Art response patterns with HATEOAS support
Implements best practices from the comprehensive guide:
- Consistent response format across all endpoints
- HATEOAS links for API discoverability
- Detailed metadata for pagination and tracing
- Type-safe response models
"""
from __future__ import annotations
from datetime import UTC, datetime, timezone
from enum import Enum
from typing import Any, Dict, Generic, List, Optional, TypeVar, Union
from fastapi import status
from pydantic import BaseModel, ConfigDict, Field
T = TypeVar("T")
class ResponseStatus(str, Enum):
"""Standard response status values"""
SUCCESS = "success"
ERROR = "error"
PARTIAL = "partial"
PENDING = "pending"
class PaginationMeta(BaseModel):
"""
Pagination metadata following REST best practices
Standards Compliance: REST API Pagination Pattern
"""
model_config = ConfigDict(frozen=True)
page: int = Field(..., ge=1, description="Current page number (1-indexed)")
per_page: int = Field(..., ge=1, le=1000, description="Items per page")
total: int = Field(..., ge=0, description="Total number of items")
total_pages: int = Field(..., ge=0, description="Total number of pages")
has_next: bool = Field(..., description="Whether there is a next page")
has_prev: bool = Field(..., description="Whether there is a previous page")
class HATEOASLink(BaseModel):
"""
HATEOAS link for API discoverability
Standards Compliance: HATEOAS (Hypermedia as the Engine of Application State)
"""
href: str = Field(..., description="URL to the linked resource")
rel: str = Field(..., description="Relationship type (self, next, prev, etc.)")
method: str = Field(default="GET", description="HTTP method for the link")
title: str | None = Field(None, description="Human-readable link description")
class ResponseMeta(BaseModel):
"""
Response metadata with observability support
Includes:
- Request tracing (request_id, trace_id)
- Timing information
- Pagination data
- HATEOAS links
"""
model_config = ConfigDict(frozen=True)
timestamp: datetime = Field(
default_factory=lambda: datetime.now(UTC), description="Response timestamp (UTC)"
)
request_id: str = Field(..., description="Unique request identifier for tracing")
trace_id: str | None = Field(None, description="Distributed tracing ID (OpenTelemetry)")
duration_ms: float | None = Field(
None, ge=0, description="Request processing time in milliseconds"
)
pagination: PaginationMeta | None = Field(None, description="Pagination metadata")
links: list[HATEOASLink] | None = Field(None, description="HATEOAS navigation links")
api_version: str = Field(default="v1", description="API version")
class ErrorDetail(BaseModel):
"""
Detailed error information with context
Standards Compliance: RFC 7807 Problem Details for HTTP APIs
"""
model_config = ConfigDict(frozen=True)
code: str = Field(..., description="Machine-readable error code")
message: str = Field(..., description="Human-readable error message")
field: str | None = Field(None, description="Field name for validation errors")
details: dict[str, Any] | None = Field(None, description="Additional error context")
suggestion: str | None = Field(None, description="How to fix the error")
documentation_url: str | None = Field(None, description="Link to relevant documentation")
class StandardErrorResponse(BaseModel):
"""
Standard error response format
Clinical Context: Clear error communication is critical in healthcare to prevent
misinterpretation and ensure proper action can be taken.
Standards Compliance: RFC 7807, FHIR OperationOutcome pattern
"""
model_config = ConfigDict(frozen=True)
status: ResponseStatus = Field(default=ResponseStatus.ERROR, description="Response status")
error: ErrorDetail = Field(..., description="Error details")
meta: ResponseMeta = Field(..., description="Response metadata")
class StandardSuccessResponse(BaseModel, Generic[T]):
"""
Standard success response format with generic data type
Clinical Context: Consistent response structure helps clinical systems
reliably parse and display data.
Performance: Target <200ms p95 for all API endpoints
Example:
```python
response = StandardSuccessResponse(
status=ResponseStatus.SUCCESS,
data={"patient_id": "12345", "name": "John Doe"},
meta=ResponseMeta(request_id="req-abc123")
)
```
"""
status: ResponseStatus = Field(default=ResponseStatus.SUCCESS, description="Response status")
data: T = Field(..., description="Response payload")
meta: ResponseMeta = Field(..., description="Response metadata")
message: str | None = Field(None, description="Optional success message")
class StandardListResponse(BaseModel, Generic[T]):
"""
Standard response for list/collection endpoints
Includes pagination metadata and HATEOAS links automatically.
Performance: Implements keyset pagination for large datasets (>10K records)
Example:
```python
response = StandardListResponse(
status=ResponseStatus.SUCCESS,
data=[patient1, patient2, patient3],
meta=ResponseMeta(
request_id="req-xyz",
pagination=PaginationMeta(
page=1, per_page=20, total=150,
total_pages=8, has_next=True, has_prev=False
)
)
)
```
"""
status: ResponseStatus = Field(default=ResponseStatus.SUCCESS, description="Response status")
data: list[T] = Field(..., description="Array of items")
meta: ResponseMeta = Field(..., description="Response metadata with pagination")
message: str | None = Field(None, description="Optional message")
class HealthCheckResponse(BaseModel):
"""
Standard health check response
Standards Compliance: Kubernetes liveness/readiness probe pattern
Performance: Health checks must respond in <50ms
"""
model_config = ConfigDict(frozen=True)
status: str = Field(..., description="Overall health status (healthy, degraded, unhealthy)")
version: str = Field(..., description="Application version")
timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
checks: dict[str, dict[str, Any]] = Field(..., description="Individual component health")
uptime_seconds: float = Field(..., ge=0, description="Application uptime")
# Helper functions for creating standardized responses
def success_response(
data: Any,
request_id: str | None = None,
trace_id: str | None = None,
message: str | None = None,
links: list[HATEOASLink] | None = None,
duration_ms: float | None = None,
api_version: str = "v1",
) -> StandardSuccessResponse:
"""
Create a standardized success response
Args:
data: Response payload
request_id: Unique request identifier (auto-generated if not provided)
trace_id: OpenTelemetry trace ID
message: Optional success message
links: HATEOAS navigation links
duration_ms: Request processing time
api_version: API version
Returns:
Standardized success response
"""
import uuid
if request_id is None:
request_id = f"req-{uuid.uuid4().hex[:12]}"
meta = ResponseMeta( # type: ignore[call-arg, call-overload, no-redef]
request_id=request_id,
trace_id=trace_id,
duration_ms=duration_ms,
links=links,
api_version=api_version,
)
return StandardSuccessResponse(
status=ResponseStatus.SUCCESS, data=data, meta=meta, message=message
)
def list_response(
data: list[Any],
request_id: str | None = None,
page: int = 1,
per_page: int = 20,
total: int | None = None,
trace_id: str | None = None,
links: list[HATEOASLink] | None = None,
duration_ms: float | None = None,
api_version: str = "v1",
) -> StandardListResponse:
"""
Create a standardized list/collection response with pagination
Args:
data: Array of items
request_id: Unique request identifier (auto-generated if not provided)
page: Current page number (default: 1)
per_page: Items per page (default: 20)
total: Total number of items (calculated from data if not provided)
trace_id: OpenTelemetry trace ID
links: HATEOAS navigation links
duration_ms: Request processing time
api_version: API version
Returns:
Standardized list response with pagination
"""
import math
import uuid
if request_id is None:
request_id = f"req-{uuid.uuid4().hex[:12]}"
if total is None:
total = len(data)
total_pages = math.ceil(total / per_page) if per_page > 0 else 0
has_next = page < total_pages
has_prev = page > 1
pagination = PaginationMeta(
page=page,
per_page=per_page,
total=total,
total_pages=total_pages,
has_next=has_next,
has_prev=has_prev,
)
meta = ResponseMeta(
request_id=request_id,
trace_id=trace_id,
duration_ms=duration_ms,
pagination=pagination,
links=links,
api_version=api_version,
)
return StandardListResponse( # type: ignore[call-arg, call-overload, no-redef]
status=ResponseStatus.SUCCESS, data=data, meta=meta
)
def error_response(
code: str,
message: str,
status_code: int = 400,
request_id: str | None = None,
trace_id: str | None = None,
field: str | None = None,
details: dict[str, Any] | None = None,
suggestion: str | None = None,
documentation_url: str | None = None,
duration_ms: float | None = None,
api_version: str = "v1",
) -> StandardErrorResponse:
"""
Create a standardized error response
Args:
code: Machine-readable error code
message: Human-readable error message
status_code: HTTP status code (default: 400)
request_id: Unique request identifier (auto-generated if not provided)
trace_id: OpenTelemetry trace ID
field: Field name for validation errors
details: Additional error context
suggestion: How to fix the error
documentation_url: Link to relevant documentation
duration_ms: Request processing time
api_version: API version
Returns:
Standardized error response
"""
import uuid
if request_id is None:
request_id = f"req-{uuid.uuid4().hex[:12]}"
error_detail = ErrorDetail(
code=code,
message=message,
field=field,
details=details,
suggestion=suggestion,
documentation_url=documentation_url,
)
meta = ResponseMeta( # type: ignore[call-arg, call-overload, no-redef]
request_id=request_id, trace_id=trace_id, duration_ms=duration_ms, api_version=api_version
)
return StandardErrorResponse(status=ResponseStatus.ERROR, error=error_detail, meta=meta)
# Standard error codes
class ErrorCodes:
"""Standard error codes for YAZ Care Platform"""
# Authentication & Authorization (1xxx)
UNAUTHORIZED = "AUTH_1001"
INVALID_TOKEN = "AUTH_1002"
TOKEN_EXPIRED = "AUTH_1003"
INSUFFICIENT_PERMISSIONS = "AUTH_1004"
MFA_REQUIRED = "AUTH_1005"
# Validation (2xxx)
VALIDATION_ERROR = "VAL_2001"
INVALID_INPUT = "VAL_2002"
MISSING_REQUIRED_FIELD = "VAL_2003"
INVALID_FORMAT = "VAL_2004"
# Resource Management (3xxx)
RESOURCE_NOT_FOUND = "RES_3001"
RESOURCE_ALREADY_EXISTS = "RES_3002"
RESOURCE_CONFLICT = "RES_3003"
RESOURCE_DELETED = "RES_3004"
# Multi-Tenancy (4xxx)
TENANT_NOT_FOUND = "TNT_4001"
TENANT_ISOLATION_VIOLATION = "TNT_4002"
TENANT_QUOTA_EXCEEDED = "TNT_4003"
TENANT_SUSPENDED = "TNT_4004"
# Clinical Operations (5xxx)
CLINICAL_VALIDATION_ERROR = "CLN_5001"
UNSAFE_OPERATION = "CLN_5002"
PROTOCOL_VIOLATION = "CLN_5003"
INVALID_CLINICAL_DATA = "CLN_5004"
# System Errors (9xxx)
INTERNAL_SERVER_ERROR = "SYS_9001"
SERVICE_UNAVAILABLE = "SYS_9002"
DATABASE_ERROR = "SYS_9003"
EXTERNAL_SERVICE_ERROR = "SYS_9004"
RATE_LIMIT_EXCEEDED = "SYS_9005"