-
Notifications
You must be signed in to change notification settings - Fork 299
Error Pointers for APIViews #1044
-
Hello!
I have an API view which inherits from rest_framework.views.APIView, rather than GenericAPIView. Before (I believe) PR #986 was merged, formatting for required field errors used field names, e.g.:
{
"errors": [
{
"detail": "This field is required.",
"status": "400",
"source": {
"pointer": "/data/attributes/address"
},
"code": "required"
}
]
}
Because pointers are now set only if the view inherits from GenericAPIView, required field errors are now much less informative:
{
"errors": [
{
"detail": "This field is required.",
"status": "400",
"code": "required"
}
]
}
It doesn't make sense for my API view to inherit from GenericAPIView, because it provides the result of a calculation rather than directly returning model data. Would it be possible to reinstate the previous behavior in cases like this?
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
Thanks for your feedback.
Before the fix of #986 the error pointer base was hard coded and was only correct in some cases and in other it was not. And the only way which seemed plausible is to make calculation based on the GenericAPIView as this is the lowest view class which enforces setting of serializer class. And the serializer class is needed to determine the correct pointer.
This said we might change this check but for this it is important to know the different APIView use cases.
So could you paste your APIView here to see how you have configured it? Thanks.
Beta Was this translation helpful? Give feedback.
All reactions
-
The API view (code example below) does use a serializer. Perhaps an alternate solution could involve manually declaring a serializer attribute?
class CalculationView(APIView):
permission_classes = (IsAuthenticated,)
@swagger_auto_schema(
query_serializer=CalculationSerializer,
responses=custom_view_to_response("get", "CalculationView"),
)
def get(self, request, format=None):
param_serializer = CalculationSerializer(data=request.GET)
param_serializer.is_valid(raise_exception=True)
calculator = Calculate(param_serializer.data)
calculator.init()
data = calculator.call()
return Response(data)
Beta Was this translation helpful? Give feedback.
All reactions
-
Thanks for the example. As you do not set resource_name in your view I assume that the data returned by calculator.call() is already in JSON:API spec format. Is this correct?
I think in such a case where the APIView is manually building the result it should also manually format the errors. For this you can overwrite handle_exception of your view and use the utility rest_framework_json_api.utils.format_error_object with a fix pointer to attributes when the exception is a single ValidationError or otherwise call super. I haven't tested this but should work in theory.
Beta Was this translation helpful? Give feedback.