Marko
Marko

Reputation: 1401

drf-spectacular: add response description

How can I add description to responses in the @extend_schema decorator?

'500':
  content:
    application/json:
      schema:
        $ref: '#/components/schemas/Error'
      description: ''

Upvotes: 10

Views: 14472

Answers (2)

Rabarberski
Rabarberski

Reputation: 24912

Insa's answer and comments led me to a working solution using OpenApiResponse (requires drf-spectacular version >=0.15)

Here's some example code of how I did it:

from drf_spectacular.utils import extend_schema, OpenApiResponse
from rest_framework import generics

class MyResourceList(generics.ListCreateAPIView):

    @extend_schema(
        summary="Create a new resource",
        responses={
            201: OpenApiResponse(response=MyCustomSerializer,
                                 description='Created. New resource in response'),
            400: OpenApiResponse(description='Bad request (something invalid)'),
        },
    )
    def post(self, request, *args, **kwargs):
        """ 
        Some explanation goes here ...
        """
        return super().post(request, *args, **kwargs)

Upvotes: 12

Insa
Insa

Reputation: 1861

that specific description location you are referring to is not easily available through the decorators. however, there are multiple places a description can be put.

  1. @extend_schema(description='Your description') this will add the description to the view action (operation). However, this is targeted to the operation itself and not the 500 Error case.

  2. adding a docstring to your Error serializer. probably what you want to do.

this part is still a bit rough as the "Error" feature is still work in progress.

Upvotes: 2

Related Questions