[Python] Python openapi_core validate_request method. How to get schema key object that failed...

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    developing my own OpenAPI (v 3.0+) with customized Spec and schemas and validate incoming Django requests data by using openapi_core library. Interesting question that i haven't found answer to...is there any possibility to find out the exact field in schema's object that didn't pass the validation? Here is some code context: So my spec looks like:


    "paths": {
    "/api/operation/": {
    "post": {
    "description": "Handle UPSERT operations for multiple sheets",
    "requestBody": {
    ...
    "schema": {
    "type": "object",
    "properties": {
    "items": {
    "oneOf": [
    {
    "$ref": "#/components/schemas/some_schema"
    }]},
    "options": {
    "type": "object",
    "properties": {
    "transaction": {
    "type": "boolean"
    },
    "validate_only": {
    "type": "boolean"
    }
    }..},
    "required": [
    "sheets"
    ]}..}
    ...
    "components": {
    "schemas": {
    "some_schema": {
    ...
    }...etc.


    so i need to get for example id when calling validate_request.


    Curently i perform the following validation: try: openapi.validate_request(request_wrapped) --> here is the validation

    #and here below i catch exception when request body is invalid

    except InvalidRequestBody as e:
    if e.__cause__ and hasattr(e.__cause__, 'schema_errors'):
    error_messages = []
    for error in e.__cause__.schema_errors:
    error_info = {'message': str(error.context)}
    error_messages.append(error_info)
    logger.error(f"\nInvalid request body errors: {error_messages}")
    return Response({
    'status': 'error',
    'message': 'Invalid request body',
    'debug_info': {
    'error_type': 'InvalidRequestBody',
    'validation_errors': error_messages # Use the converted list
    }
    }, status=status.HTTP_400_BAD_REQUEST)
    else: ...



    but maximum i can have is the error LIKE (when passing 1 instead of "1" element to a string field "unit"):

    <ValidationError: "1 is not of type 'string'">

    but i don't see any keys i can select to return more informative answer ...

    p.s. not a guru in OpenAPI specifications and data validation, openapi_core is the most ideal library i have found for now...

    Continue reading...

Compartilhe esta Página