whitebear
whitebear

Reputation: 12437

To pass the Response from the nested function `Django REST framework`

I am using python django with Django REST framework

It can return the Reponse to the browser like this, in the views.py

from rest_framework.response import Response
    @api_view(['GET'])
    def get_by(request):
        res = {"test":"answer"}
        return Response(res)

I want to pass the Response to the browser where nested function

from rest_framework.response import Response
    @api_view(['GET'])
    def get_by(request):
        x(t)

def x():
   #error happens here!!
    res = {"error":"error happens!!"}
    return Response(res)

in this case, it is simple, I can return the error to the first function and first function can return the error Response.

but when you have three four,five nested function?

What is the best practice?

Upvotes: 0

Views: 256

Answers (2)

Kyell
Kyell

Reputation: 636

As mentioned in the previous answer you can use a custom APIException inside the function to stop the api handler midway. If you dont want it to return like a system error, you can set the response status code like the example below:

from rest_framework.exceptions import APIException
from rest_framework import status

class OkException(APIException):
    status_code = status.HTTP_200_OK
    default_detail = "error happens!!"
    default_code = "error_happens"

You can then raise it inside the function like a normal exception

raise OkException()

Upvotes: 1

It should better use serializer or services and handle some validation on that.

https://www.django-rest-framework.org/api-guide/serializers/#validation

On the other side, you can develop some customized APIExcepetion and just raised them.

https://www.django-rest-framework.org/api-guide/exceptions/#api-reference

Upvotes: 1

Related Questions