Home > Back-end >  Can an APIView group multiple GET and POST methods?
Can an APIView group multiple GET and POST methods?

Time:01-08

I am implementing an API for a game using DRF view (more specifically APIViews). I have figured out how to use more than one serializer for a view but I need this view to combine multiple models and think that I need more than one GET as well as more than one POST method. Is this even possible? My code so far looks like this:

class GameView(APIView):
    """
    API View that retrieves the game, allows users to post stuff and finally a game session is posted as well once the 5 game rounds have been completed
    """
    serializer_class = GametypeSerializer
    serializer_class = GamesessionSerializer
    serializer_class = GameroundSerializer

    serializer_class = ResourceSerializer
    serializer_class = VerifiedLabelSerializer
    serializer_class = LabelSerializer

    def get_serializer_class(self):
        if self.request.method == 'POST':
            return YOUR_SERIALIZER_1
        elif self.request.method == 'GET':
            return YOUR_SERIALIZER_2
        else:
            return YOUR_DEFAULT_SERIALIZER

    def get_queryset(self):

        gametypes = Gametype.objects.all().filter(name="labeler")

        return gametypes

    def get(self, request, *args, **kwargs):
        # gets a resource and an empty game round object to be completed (according to the game type chosen by the user)

    def post(self, request, *args, **kwargs):
        # users post a label, that is saved in the label model, a verified model is saved in the verified label model. Once 2 game rounds have been completed, a game session is posted.

I think it is worth mentioning that I plan on using a single url for this. It should work like this: a user clicks a game type and then this view is called and the game starts and everything is handled that needs to be handled during the game.

CodePudding user response:

If you really want to use just one url you can get it done with GET parameters.

def get(self, request, *args, **kwargs):
    model = request.GET.get("model")
    if model == "Gametype":
        .. do something with the Gametype model ..
    elif model == "Resource":
        .. do something with the Resource model ..

same for get_serializer_class() so you know which serializer to use.

Then you would call /gameview/?model=Gametype or /gameview/?model=Resource

But what's so wrong about using multiple urls in the first place?

  •  Tags:  
  • Related