Title: [Feature]: Support for injecting custom input in custom openapi error response format · Issue #910 · python-openapi/openapi-core · GitHub
Open Graph Title: [Feature]: Support for injecting custom input in custom openapi error response format · Issue #910 · python-openapi/openapi-core
X Title: [Feature]: Support for injecting custom input in custom openapi error response format · Issue #910 · python-openapi/openapi-core
Description: Suggested Behavior I would like to add a way to customize error response format and would like to add additional information in the error response generated by OpenAPI-Core currently the error response generated by OpenAPI-Core is as fol...
Open Graph Description: Suggested Behavior I would like to add a way to customize error response format and would like to add additional information in the error response generated by OpenAPI-Core currently the error resp...
X Description: Suggested Behavior I would like to add a way to customize error response format and would like to add additional information in the error response generated by OpenAPI-Core currently the error resp...
Opengraph URL: https://github.com/python-openapi/openapi-core/issues/910
X: @github
Domain: patch-diff.githubusercontent.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"[Feature]: Support for injecting custom input in custom openapi error response format","articleBody":"### Suggested Behavior\r\n\r\nI would like to add a way to customize error response format and would like to add additional information in the error response generated by OpenAPI-Core\r\n\r\ncurrently the error response generated by OpenAPI-Core is as follows\r\n```\r\n{\r\n \"errors\": [\r\n {\r\n \"class\": \"\u003cclass 'openapi_core.validation.schemas.exceptions.InvalidSchemaValue'\u003e\",\r\n \"status\": 400,\r\n \"title\": \"Value {'flag': 'testF'} not valid for schema of type object: (\u003cValidationError: \\\"'testF' is too short\\\"\u003e,)\"\r\n }\r\n ]\r\n}\r\n```\r\n\r\nI want to customize the response in following format\r\n\r\n```\r\n{\r\n \"title\": \"Failed to execute your favorite API\" \\\\ Custom String provided by code\r\n\"causedBy\": [\r\n \"Value {'flag': 'testF'} not valid for schema of type object: (\u003cValidationError: \\\"'testF' is too short\\\" \\\\ Error Resposne generated by OpenAPI Core\r\n ]\r\n}\r\n```\r\n\r\nAs you can see in the comments, the message in causedBy field includes error messages generated by OpenAPI Core module\r\nwhereas the message in title field includes data generated and injected by actual code\r\n\r\n### Why is this needed?\r\n\r\nThis is required to make OpenAPI core more flexible and customizable and become a better choice for openapi linters and validators.\r\n\r\nAlso If OpenAPI does not support cutomization on the content of response, then it would be a deal breaker for most of the implementation as most of the projects tries to maintain some standard format of response\r\n\r\n### References\r\n\r\nI came across `FlaskOpenAPIErrorsHandler class` and created a custom handler class which inherits from FlaskOpenAPIErrorsHandler class\r\n\r\nI used constructor of this class to inject custom fields and generate custom response accordingly.\r\n\r\nfollowing is my Flask code **server.py**\r\n```\r\n#!/usr/bin/python3\r\n\"\"\"Test server.\"\"\"\r\n\r\nfrom flask import Flask, request, jsonify\r\nfrom openapi_core.contrib.flask.decorators import FlaskOpenAPIViewDecorator, FlaskOpenAPIErrorsHandler\r\nfrom openapi_core import Spec\r\n\r\n# Custom Error Handler block\r\nclass MyCustomErrorHandler(FlaskOpenAPIErrorsHandler):\r\n \"\"\"\"Custom Error Handler\"\"\"\r\n def __init__(self, title:str):\r\n self.title = title\r\n\r\n def handle(self, errors:list):\r\n response_object = jsonify({\r\n \"title\": self.title,\r\n \"causedBy\" : [self.handle_error(error) for error in errors]\r\n })\r\n response_object.error_code = 400\r\n return response_object\r\n\r\n def handle_error(self, error):\r\n \"\"\"\r\n Converts error object into error string message\r\n\r\n :param error: Error object which stores exception message\r\n :type error: Exception object\r\n :return: Error message string corresponding to error object\r\n :rtype: str\r\n \"\"\"\r\n if error.__cause__ is not None:\r\n error = error.__cause__\r\n return str(error)\r\n\r\nSPEC = \"test.yaml\"\r\napp = Flask(__name__)\r\n\r\nspec_object = Spec.from_file_path(SPEC)\r\nmy_error_handler_object = MyCustomErrorHandler(\"Failed to execute test API\")\r\nopenapi_decorator = FlaskOpenAPIViewDecorator.from_spec(spec_object, openapi_errors_handler=my_error_handler_object)\r\n\r\n@app.route(\"/test\", methods=[\"POST\"])\r\n@openapi_decorator\r\ndef read_permission():\r\n \"\"\"Test function\"\"\"\r\n temp = jsonify({\r\n \"stri_normal_json\": request.json.get(\"flag\", 1)\r\n })\r\n print(dir(temp))\r\n return temp\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host=\"0.0.0.0\", port=345, debug=True)\r\n\r\n#Valid request: curl -X POST http://localhost:345/test --data '{\"flag\":\"rohana\"}' -H 'Content-Type: application/json'\r\n\r\n#Invalid Request: curl -X POST http://localhost:345/test --data '{\"flag\":\"rohan\"}' -H 'Content-Type: application/json'\r\n```\r\n\r\nFollowing is OpenAPI Spec\r\n\r\n**test.yaml**\r\n```\r\nopenapi: '3.0.2'\r\ninfo:\r\n title: Test Title\r\n version: '1.0'\r\nservers:\r\n - url: http://localhost:345/\r\npaths:\r\n /test:\r\n post:\r\n requestBody:\r\n content:\r\n application/json:\r\n schema:\r\n type: object\r\n required:\r\n - flag\r\n properties:\r\n flag:\r\n x-pii: true\r\n type: string\r\n pattern: \"^[\\\\w.-]*$\"\r\n minLength: 6\r\n maxLength: 20\r\n responses:\r\n 200:\r\n description: Sample response\r\n content:\r\n application/json:\r\n schema:\r\n type: object\r\n properties:\r\n stri_normal_json:\r\n type: string\r\n minLength: 6\r\n maxLength: 20\r\n```\r\n\r\nAs we can see in code, I am creating object of custom error handler and injecting custom string as part of constructor in above example following is the line\r\n```\r\nmy_error_handler_object = MyCustomErrorHandler(\"Failed to execute test API\")\r\n```\r\n\r\nFollowing is the output of curl request\r\n\r\n# Invalid Curl Request\r\n```\r\nroot@ip-10-31-1-220:~/playground# curl -X POST http://localhost:345/test --data '{\"flag\":\"rohan\"}' -H 'Content-Type: application/json'\r\n{\r\n \"causedBy\": [\r\n \"Value {'flag': 'rohan'} not valid for schema of type object: (\u003cValidationError: \\\"'rohan' is too short\\\"\u003e,)\"\r\n ],\r\n \"title\": \"Failed to execute test API\"\r\n}\r\n```\r\n\r\n# Valid Curl Request\r\n```\r\nroot@ip-10-31-1-220:~/playground# curl -X POST http://localhost:345/test --data '{\"flag\":\"rohana\"}' -H 'Content-Type: application/json'\r\n{\r\n \"stri_normal_json\": \"rohana\"\r\n}\r\n```\r\nIn this way I was able to customize the response body and also inject my custom string when I create object of custom error handler. which was working fine till OpenAPI 0.16.x but **it started failing since OpenAPI 0.18.x**\r\n\r\nthis issue happened due to following pull request\r\nhttps://github.com/python-openapi/openapi-core/commit/22ace6d39607ef769ba0a36e8a24dc6df704a620\r\n\r\n### Would you like to implement a feature?\r\n\r\nYes","author":{"url":"https://github.com/rohan-97","@type":"Person","name":"rohan-97"},"datePublished":"2024-09-03T16:42:12.000Z","interactionStatistic":{"@type":"InteractionCounter","interactionType":"https://schema.org/CommentAction","userInteractionCount":0},"url":"https://github.com/910/openapi-core/issues/910"}
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:533cc5a6-47f6-6181-a8dd-c492c4c572ce |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D08A:2477FA:896678:BC1E40:69775A42 |
| html-safe-nonce | ba48a8710e352c787a940af26e0374c4e8ba7391f00729642dbbc29b0f941db5 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMDhBOjI0NzdGQTo4OTY2Nzg6QkMxRTQwOjY5Nzc1QTQyIiwidmlzaXRvcl9pZCI6IjQ1MzYxNDkyNDQ5NTEwOTE3NzgiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | 242bc5376be5f98799ce378d072ac12174c811dd81f33512d75489d89b34380e |
| hovercard-subject-tag | issue:2503328483 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python-openapi/openapi-core/910/issue_layout |
| twitter:image | https://opengraph.githubassets.com/5e6583b91d74e4e0f06545bfac658055133a2711d6bcb3c1c2622a0bf2f7f039/python-openapi/openapi-core/issues/910 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/5e6583b91d74e4e0f06545bfac658055133a2711d6bcb3c1c2622a0bf2f7f039/python-openapi/openapi-core/issues/910 |
| og:image:alt | Suggested Behavior I would like to add a way to customize error response format and would like to add additional information in the error response generated by OpenAPI-Core currently the error resp... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | rohan-97 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 3310064f35a62c06a4024ba37f41c06836f39376a095c2dfd2c4b693c34965be |
| turbo-cache-control | no-preview |
| go-import | github.com/python-openapi/openapi-core git https://github.com/python-openapi/openapi-core.git |
| octolytics-dimension-user_id | 126442889 |
| octolytics-dimension-user_login | python-openapi |
| octolytics-dimension-repository_id | 104200746 |
| octolytics-dimension-repository_nwo | python-openapi/openapi-core |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 104200746 |
| octolytics-dimension-repository_network_root_nwo | python-openapi/openapi-core |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 67d5f8d1d53c3cc4f49fc3bb8029933c3dc219e6 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width