Skip to content

BYNT-1389: Standardize API Responses#131

Merged
tarekio merged 28 commits intomainfrom
bynt-1389-standardize-api-responses
Aug 1, 2025
Merged

BYNT-1389: Standardize API Responses#131
tarekio merged 28 commits intomainfrom
bynt-1389-standardize-api-responses

Conversation

@cango91
Copy link
Contributor

@cango91 cango91 commented Jul 10, 2025

Jira Issue

  1. BYNT-1389

Description

⚠️ Introduces breaking API changes ⚠️

  • Adds json_error and json_ok helper methods in HTTPResponse class.
  • All endpoints return data or errors with the new standardized format
  • All creation endpoints updated to return 201 with the newly created object à la A/B/I create endpoints
  • API docs updated to reflect changes

Checklist

  • Tests added/updated
  • Documentation updated (if needed)
  • New strings prepared for translations

API Changes (if applicable)

  • Permissions checked
  • Endpoint tests added

Additional Notes

[Any other relevant information]

cango91 added 3 commits July 11, 2025 11:34
- use HTTPResponse.json_ok and HTTPResponse.json_error to standardize api responses across all `views.py` files
- update all tests to use the new response models
- fix: use `DateHelper` to properly serialize datetime fields in `Session` model
@cango91 cango91 self-assigned this Jul 11, 2025
@cango91 cango91 changed the title standardize to json - preserving most codes and return structure. tes… BYNT-1389: Standardize API Responses Jul 14, 2025
@cango91 cango91 marked this pull request as ready for review July 14, 2025 16:35
response_data = {"message": message}
if errors:
response_data["errors"] = errors
return Response(json.dumps(response_data), status=status, content_type="application/json")

Check warning

Code scanning / CodeQL

Information exposure through an exception Medium

Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information
flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.
Stack trace information flows to this location and may be exposed to an external user.

Copilot Autofix

AI 8 months ago

To fix the issue, we need to ensure that sensitive information, such as stack traces, is not exposed to the client. Instead, we should log the detailed error message on the server and return a generic error message to the client. Specifically:

  1. Modify the HTTPResponse.error method in enferno/utils/http_response.py to accept an optional log_message parameter. This parameter will be used for logging detailed error information, while the message parameter will contain a generic error message for the client.
  2. Update the exception handling in enferno/admin/views.py to log the exception details and pass a generic error message to HTTPResponse.error.

Suggested changeset 2
enferno/utils/http_response.py

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/enferno/utils/http_response.py b/enferno/utils/http_response.py
--- a/enferno/utils/http_response.py
+++ b/enferno/utils/http_response.py
@@ -21,4 +21,7 @@
     @staticmethod
-    def _json_error(message: str, status: int = 400, errors: Any = None) -> Response:
+    def _json_error(message: str, status: int = 400, errors: Any = None, log_message: str | None = None) -> Response:
         """Standard JSON response for error."""
+        if log_message:
+            # Log the detailed error message
+            current_app.logger.error(log_message)
         response_data = {"message": message}
@@ -41,5 +44,5 @@
     @staticmethod
-    def error(message: str, status: int = 400, errors: Any = None) -> Response:
+    def error(message: str, status: int = 400, errors: Any = None, log_message: str | None = None) -> Response:
         """Error response with custom status"""
-        return HTTPResponse._json_error(message, status, errors)
+        return HTTPResponse._json_error(message, status, errors, log_message)
 
EOF
@@ -21,4 +21,7 @@
@staticmethod
def _json_error(message: str, status: int = 400, errors: Any = None) -> Response:
def _json_error(message: str, status: int = 400, errors: Any = None, log_message: str | None = None) -> Response:
"""Standard JSON response for error."""
if log_message:
# Log the detailed error message
current_app.logger.error(log_message)
response_data = {"message": message}
@@ -41,5 +44,5 @@
@staticmethod
def error(message: str, status: int = 400, errors: Any = None) -> Response:
def error(message: str, status: int = 400, errors: Any = None, log_message: str | None = None) -> Response:
"""Error response with custom status"""
return HTTPResponse._json_error(message, status, errors)
return HTTPResponse._json_error(message, status, errors, log_message)

enferno/admin/views.py
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/enferno/admin/views.py b/enferno/admin/views.py
--- a/enferno/admin/views.py
+++ b/enferno/admin/views.py
@@ -1382,3 +1382,4 @@
     except Exception as e:
-        return HTTPResponse.error(str(e), status=500)
+        current_app.logger.error("Error reordering location admin levels: %s", str(e))
+        return HTTPResponse.error("An internal error occurred. Please contact support.", status=500)
     return HTTPResponse.success(
EOF
@@ -1382,3 +1382,4 @@
except Exception as e:
return HTTPResponse.error(str(e), status=500)
current_app.logger.error("Error reordering location admin levels: %s", str(e))
return HTTPResponse.error("An internal error occurred. Please contact support.", status=500)
return HTTPResponse.success(
Copilot is powered by AI and may make mistakes. Always verify output.
Copy link
Collaborator

@level09 level09 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small tweaks needed.

@level09 level09 self-assigned this Jul 24, 2025
level09 and others added 14 commits July 24, 2025 19:02
- Replace incorrect 'any' with proper 'Any' from typing
- Fix dict parameter types to handle None properly (dict | None)
- Add missing return type annotations (-> Response)
- Improve type hint consistency across all methods
- Fix HTTP status codes: replace 417 with proper codes (400, 409, 500)
- Add axios response interceptor to flatten {data: {items: []}} → {items: []}
- Centralize all frontend API calls through unified api service
- Update 180+ axios calls across templates and components
- Maintain backward compatibility with existing response.data patterns
@apodacaduron apodacaduron mentioned this pull request Jul 29, 2025
5 tasks
@tarekio tarekio requested a review from level09 August 1, 2025 12:46
Resolved conflicts:
- enferno/data_import/templates/sheets-import.html: Updated to use 'api' client consistently with API standardization
- tests/data_import/test_imports.py: Added both get_first_or_fail and load_data imports

Maintained API response standardization while incorporating main branch improvements including:
- Enhanced UI components (DropField, EventsSection, IdNumberDynamicField, ImageViewer)
- Improved sheet import utilities
- Updated package dependencies
level09 added 2 commits August 1, 2025 21:55
- Replace HTTPResponse.FORBIDDEN with HTTPResponse.forbidden()
- Replace HTTPResponse.NOT_FOUND with HTTPResponse.not_found()
- Fix import path for convert_empty_strings_to_none in test
- Remove unused load_data import

This completes the API response standardization in data_import module.
- Fix import path for convert_empty_strings_to_none in test_media_categories.py
- Fix import path for convert_empty_strings_to_none in test_relation_infos.py
- Fix import path for convert_empty_strings_to_none in test_roles.py

All imports now use the correct path: enferno.utils.validation_utils
This completes the import path standardization after the merge.
@tarekio tarekio merged commit ce7328c into main Aug 1, 2025
6 of 7 checks passed
@tarekio tarekio deleted the bynt-1389-standardize-api-responses branch August 1, 2025 19:57
tarekio pushed a commit that referenced this pull request Aug 9, 2025
Several api endpoints were returning stacktrace info. This issue was introduced in #131.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants