Spaces:
Running
Running
| """ | |
| Response formatting utilities for standardized API responses. | |
| """ | |
| from typing import Any, Dict, Optional | |
| from datetime import datetime | |
| from uuid import uuid4 | |
| def success_response( | |
| data: Any, | |
| message: str = "Success", | |
| correlation_id: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Format a successful API response. | |
| Args: | |
| data: Response data | |
| message: Success message | |
| correlation_id: Optional correlation ID for request tracing | |
| Returns: | |
| Standardized success response dictionary | |
| """ | |
| return { | |
| "status": True, | |
| "data": data, | |
| "message": message, | |
| "correlation_id": correlation_id or str(uuid4()), | |
| "timestamp": datetime.utcnow().isoformat() + "Z" | |
| } | |
| def error_response( | |
| code: str, | |
| message: str, | |
| details: Optional[Dict[str, Any]] = None, | |
| correlation_id: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Format an error API response. | |
| Args: | |
| code: Error code | |
| message: Human-readable error message | |
| details: Optional additional error details | |
| correlation_id: Optional correlation ID for request tracing | |
| Returns: | |
| Standardized error response dictionary | |
| """ | |
| return { | |
| "status": False, | |
| "error": { | |
| "code": code, | |
| "message": message, | |
| "details": details or {} | |
| }, | |
| "correlation_id": correlation_id or str(uuid4()), | |
| "timestamp": datetime.utcnow().isoformat() + "Z" | |
| } | |
| def paginated_response( | |
| documents: list, | |
| total: int, | |
| page: int, | |
| limit: int, | |
| correlation_id: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Format a paginated list response. | |
| Args: | |
| documents: List of documents for current page | |
| total: Total number of documents | |
| page: Current page number | |
| limit: Page size limit | |
| correlation_id: Optional correlation ID | |
| Returns: | |
| Standardized paginated response | |
| """ | |
| has_more = (page * limit) < total | |
| return success_response( | |
| data={ | |
| "documents": documents, | |
| "total": total, | |
| "has_more": has_more, | |
| "page": page, | |
| "limit": limit | |
| }, | |
| correlation_id=correlation_id | |
| ) | |