A Django REST Framework utility for standardized API responses, pagination, and exception handling.
- Consistent Response Format: All API responses follow a standardized structure (
success,message,data, with optionalmetaanderrorsfields). - Custom Renderer: A
StandardResponseRendererthat formats all responses consistently, preventing common issues like double-wrapping. - Standardized Pagination:
StandardPaginationclass that provides rich metadata, includingcount,total_pages, andcurrent_page. - Custom Exception Handler: A handler that catches DRF exceptions and formats them into the standard error response structure.
- Helper Functions: Utilities to easily create standardized success and error responses.
{
"success": true,
"message": "Operation successful",
"data": {
"id": 1,
"name": "Item 1"
}
}{
"success": true,
"message": "Operation successful",
"data": [
{
"id": 1,
"name": "Item 1"
}
],
"meta": {
"pagination": {
"count": 100,
"next": "http://api.example.org/items?page=2",
"previous": null,
"total_pages": 10,
"current_page": 1,
"page_size": 10
}
}
}{
"success": false,
"message": "Validation failed",
"data": {},
"errors": {
"name": ["This field is required"],
"email": ["Enter a valid email address"]
}
}pip install drf-standardized-responsesAdd the following to your Django settings.py:
REST_FRAMEWORK = {
# Use the custom exception handler
'EXCEPTION_HANDLER': 'drf_standardized_responses.exceptions.standardized_exception_handler',
# Use the custom pagination class
'DEFAULT_PAGINATION_CLASS': 'drf_standardized_responses.pagination.StandardPagination',
# Use the custom renderer
'DEFAULT_RENDERER_CLASSES': [
'drf_standardized_responses.renderers.StandardResponseRenderer',
# Add other renderers if needed, like BrowsableAPIRenderer
'rest_framework.renderers.BrowsableAPIRenderer',
],
}A utility class for creating standardized API responses.
from drf_standardized_responses.responses import StandardResponse
# Create a success response
response = StandardResponse.success(
data={"key": "value"},
message="Data retrieved successfully",
meta={"custom_meta": "value"},
status_code=200
)
# Create an error response
response = StandardResponse.error(
message="Validation failed",
errors={"field": ["This field is required"]},
status_code=400
)This renderer automatically wraps your API responses in the standard structure. It correctly handles both error and success responses.
A pagination class that integrates with the standardized response format to provide consistent pagination metadata.
An exception handler that catches DRF exceptions and formats them into standardized error responses.
Run the test suite:
pytest- Yousef M. Y. Al Sabbah itzyousefalsabbah@gmail.com
- GitHub: Yosef-AlSabbah
Contributions are welcome! Please check out the contributing guidelines for more details on how to contribute to this project.
BSD-3-Clause