Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include 400 validation errors in drf-spectacular?

I want to view validation details in 400 response as they can be reutrned by the serializer. The serializer can return errors depending on a missing field or invalid value and I want the documentation to indicate which kind of errors can appear with the status code 400. Something like this

200: Success

400: [ { "organisation_id": [ "This field is required." ] } ] #include any validation errors that can come from the serializer

My code currently is this

@extend_schema(
        summary="Create a new transaction",
        responses={
            201: OpenApiResponse(
                description='Success',
            ),
            400: OpenApiResponse(
                description='Bad request. One or more errors occured.',
            ),
        },
    )

And currently this outputs 200: Success

400: Bad request. One or more errors occurred.

Is there something like

400: OpenApiResponse(description=customSerializerErrors,
 ), #customSerializerErrors is something i hope gets errors from the serializer
like image 200
Anjayluh Avatar asked Sep 19 '25 11:09

Anjayluh


1 Answers

drf-spectacular works on the basis of serializers.

OpenApiResponse is a convenience wrapper that is not needed most of the time. In fact here, it is probably not doing what you expect. You would need to give OpenApiResponse(response=SomeSerializer), otherwise you are saying there is no response body, because the default is None == no response.

You likely want to do this:

@extend_schema(
        summary="Create a new transaction",
        responses={
            201: YourSerializer,
            400: YourErrorSerializer,
        },
    )

There is no predefined YourErrorSerializer because Django's error_handler is highly dynamic and cannot be inspected. At the moment you would need to write this YourErrorSerializer yourself. Note that this serializer is not actually used, but is merely telling spectacular how the response is structured.

like image 56
Insa Avatar answered Sep 21 '25 01:09

Insa