Steven
Steven

Reputation: 15258

discover a param in APIView swagger

I have an APIView object as-is :

from rest_framework.views import APIView
from rest_framework.response import Response
from drf_yasg.utils import swagger_auto_schema

class SimulationGenerator(APIView):

    @swagger_auto_schema()
    def post(self, request) -> Response:
        """create a simulation"""
        simulation_id = request.data["simulation_id"]
        create_simulation(simulation_id)
        return Response(status=200, data=f"Job with simu_id : {simulation_id} created")

and my URL is:

from django.urls import path

from .views import SimulationGenerator

urlpatterns = [
    path("simulation/", SimulationGenerator.as_view()),
]

Having this, my API is called doing :

POST simulation/

with a body :

{ 
     "simulation_id" : "foo"
}

But when I call my swagger, my params are empty :

"post": {
    "parameters": [],

How can I make swagger_auto_schema discover that I need a simulation_id param ?

Upvotes: 0

Views: 103

Answers (1)

IamFr0ssT
IamFr0ssT

Reputation: 769

Try to use DRF Serializers to declare required request field.

class SimulationIdSerializer(serializers.Serializer):
    simulation_id = serializers.IntegerField()

and use it like:

...
class SimulationGenerator(APIView):

    @swagger_auto_schema(method='post', request_body=SimulationIdSerializer)
    def post(self, request) -> Response:
        """create a simulation"""
...

drf-yasg has docs and an example project. This is not the only way to specify parameters and response classes.

Upvotes: 1

Related Questions