from typing import Any from fastapi import FastAPI from fastapi.openapi.constants import REF_PREFIX from fastapi.openapi.utils import get_openapi field_error_definition = { "title": "FieldError", "type": "object", "properties": { "message": {"title": "Message", "type": "string"}, "code": {"title": "Error code", "type": "string"}, }, "required": ["message", "code"], } validation_error_response_definition = { "title": "HTTPValidationError", "type": "object", "properties": { "message": {"title": "Message", "type": "string"}, "code": {"title": "Error code", "type": "string"}, "fields": { "title": "Field errors", "type": "object", "additionalProperties": {"$ref": REF_PREFIX + "FieldError"}, }, }, "required": ["message", "code", "fields"], "example": { "message": "Validation error", "code": "validation_error", "fields": { "name": { "message": "Cannot be blank", "code": "value_error.required", }, "email": { "message": "Not valid email", "code": "value_error.invalid", }, }, }, } def extend(app: FastAPI) -> None: def _openapi() -> dict[str, Any]: if app.openapi_schema: return app.openapi_schema openapi_schema = get_openapi( title=app.title, version=app.version, openapi_version=app.openapi_version, description=app.description, servers=app.servers, routes=app.routes, ) del openapi_schema["components"]["schemas"]["ValidationError"] openapi_schema["components"]["schemas"].update( { "FieldError": field_error_definition, "HTTPValidationError": validation_error_response_definition, } ) app.openapi_schema = openapi_schema return app.openapi_schema app.openapi = _openapi # type: ignore[method-assign]