A package for handling responses with potential errors and generic data, including predefined and custom error handling. This package is used as a complement to exceptions to have more control over business logic errors.
Project description
Response Handler
A Python library for handling HTTP responses and error management in a consistent and type-safe way.
Features
- Type-safe Response Handling: Built with Pydantic for robust data validation and serialization
- Either Pattern: Functional error handling with
Eithertype for success/failure cases - HTTP Status Code Management: Automatic status code mapping based on error types
- Context Support: Add contextual information to responses and errors
- JSON Serialization: Built-in JSON serialization with customizable output
- OpenAPI/Swagger Support: Automatic schema generation for API documentation
- HTTP Interceptor: Built-in HTTP request handling with automatic error mapping
- Detailed Error Information: Support for additional error context and where information
- Python 3.8+ Support: Compatible with Python versions 3.8 through 3.12
Installation
pip install response_handler_lib
Quick Start
from response_handler_lib import Response, Either, Success, Failure, ErrorItem
from response_handler_lib.http_interceptor import HTTPInterceptor
# Create a successful response
response = Response(data={"message": "Hello, World!"})
print(response.to_json())
# Output: {"data": {"message": "Hello, World!"}, "errors": [], "context": {}, "status_code": 200}
# Create a response with an error
error = ErrorItem.create("VAL_ERROR", "Invalid input", "The input value was invalid")
response = Response(errors=[error])
print(response.to_json())
# Output: {"data": null, "errors": [{"code": "VAL_ERROR", "message": "Invalid input", "where": "The input value was invalid"}], "context": {}, "status_code": 400}
# Use Either for functional error handling
def process_data(data):
if not data:
return Failure([ErrorItem.create("VAL_ERROR", "Data is required", "No data provided")])
return Success({"processed": data})
# Convert Either to Response
either = process_data(None)
response = Response.from_either(either)
print(response.to_json())
# Output: {"data": null, "errors": [{"code": "VAL_ERROR", "message": "Data is required", "where": "No data provided"}], "context": {}, "status_code": 400}
# Use HTTP Interceptor for making requests
interceptor = HTTPInterceptor()
response = interceptor.request('GET', 'https://api.example.com/data')
print(response.to_json())
Real-World Examples
User Registration Validation
def validate_user_registration(email: str, password: str, username: str) -> Either[List[ErrorItem], Dict]:
errors = []
# Validate email
if '@' not in email:
errors.append(ErrorItem.create(
"INVALID_EMAIL",
"The email format is not valid",
f"Invalid email format: {email}"
))
# Validate password
if len(password) < 8:
errors.append(ErrorItem.create(
"PASSWORD_TOO_SHORT",
"Password must be at least 8 characters long",
f"Password length: {len(password)}"
))
if errors:
return Failure(errors)
return Success({
"email": email,
"username": username,
"status": "registered"
})
Payment Processing
def process_payment(amount: float, currency: str) -> Either[ErrorItem, Dict]:
if amount <= 0:
return Failure(ErrorItem.create(
"INVALID_AMOUNT",
"Amount must be greater than zero",
f"The amount is {amount}"
))
valid_currencies = ["USD", "EUR", "MXN"]
if currency not in valid_currencies:
return Failure(ErrorItem.create(
"INVALID_CURRENCY",
f"Unsupported currency. Valid currencies are: {', '.join(valid_currencies)}",
f"Provided currency: {currency}"
))
return Success({
"transaction_id": "TXN123456",
"amount": amount,
"currency": currency,
"status": "completed"
})
Error Types and Status Codes
The library automatically maps error types to appropriate HTTP status codes:
VAL_ERROR→ 400 (Bad Request)AUTH_ERROR→ 401 (Unauthorized)FORB_ERROR→ 403 (Forbidden)NOT_ERROR→ 404 (Not Found)TIM_ERROR→ 408 (Request Timeout)INT_ERROR→ 500 (Internal Server Error)
Configuration
from response_handler_lib import Config
# Enable context in JSON output
Config.ENABLE_CONTEXT_IN_JSON = True
# Enable 'where' field in error output
Config.ENABLE_WHERE_IN_JSON = True
# Enable logging
Config.ENABLE_LOGS = True
Advanced Features
Success.of() Factory Method
The library provides a factory method for creating Success instances with explicit type information:
from response_handler_lib import Success
# Create a Success instance with explicit type
success = Success.of({"key": "value"}) # Type: Success[L, Dict[str, str]]
Customizable JSON Output
The library allows you to customize the JSON output by controlling which fields are included:
from response_handler_lib import Config, Response
# Disable context in JSON output
Config.ENABLE_CONTEXT_IN_JSON = False
# Disable 'where' field in error output
Config.ENABLE_WHERE_IN_JSON = False
# Create a response
response = Response(data={"key": "value"})
print(response.to_json()) # Context and where fields will be excluded
Pydantic Integration
The library uses Pydantic for data validation and serialization. This provides:
- Automatic data validation
- Type checking
- JSON schema generation
- OpenAPI/Swagger integration
- Efficient serialization/deserialization
Example of Pydantic features:
from response_handler_lib import Response
from pydantic import ValidationError
# Automatic validation
try:
response = Response(status_code=999) # Will raise ValidationError
except ValidationError as e:
print(e)
# JSON schema generation
print(Response.model_json_schema())
Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License. See the LICENSE file for details.
Contact
Author: Angel Kürten
Email: angel@angelkurten.com
GitHub: angelkurten
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file response_handler_lib-0.2.1.tar.gz.
File metadata
- Download URL: response_handler_lib-0.2.1.tar.gz
- Upload date:
- Size: 19.1 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
43a84cc855768dc1db028399ce546e3e353289d8f0f5199e5d525d0ef13b0497
|
|
| MD5 |
a0ddcb161a6fef704eac3e08d201993f
|
|
| BLAKE2b-256 |
fe0c3dd2ee0ecb9267a1cf39ab888876e4c77f207736efbf44ff239f2e33ffbf
|
File details
Details for the file response_handler_lib-0.2.1-py3-none-any.whl.
File metadata
- Download URL: response_handler_lib-0.2.1-py3-none-any.whl
- Upload date:
- Size: 20.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.9.22
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
008f0eda125dd79a2d63290ddc7b214a172adc2bc5814c040571863ac700871d
|
|
| MD5 |
c0d98ec78e97af67bea91e1451eddd37
|
|
| BLAKE2b-256 |
98a479ce8be852e0c7c2fae1688adfe830287ce1bc3c0d9be840028936098c97
|