cclloyd
cclloyd

Reputation: 9205

Django Rest Framework Return 403 in Serializer

How can I return a different error code with django rest framework's serializers?

I have in my serializer.py file:

    def create(self, validated_data):
        if 'Message' not in validated_data:
            # If message is blank, don't create the message
            return PermissionDenied()

But when I do that, it just returns 201 with the body {"deleted":null} instead of returning a 403 error.

How can I make it return the 403 error?

Upvotes: 2

Views: 2643

Answers (2)

JPG
JPG

Reputation: 88539

@Marcell Erasmus's answer is nice, but it's not covered the status code part (how to return a HTTP 403 status code)

First, you need to add a Custom exception class as below,

from rest_framework import exceptions
from rest_framework import status


class CustomAPIException(exceptions.APIException):
    status_code = status.HTTP_403_FORBIDDEN
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code

and use the class wherever you want by ,

if some_condition:
    raise CustomAPIException({"some": "data"})



One of the most advantage of this particular class is that you could raise API exception with custom status codes by specifying the status_code parameter
Ex.

if some_condition:
    raise CustomAPIException({"some": "data"},status_code=status.HTTP_409_CONFLICT)

Upvotes: 4

Marcell Erasmus
Marcell Erasmus

Reputation: 914

You can override the validate_message method as follow:

from rest_framework.exceptions import ValidationError

def validate_message(self, message):
    if not message:
        raise ValidationError('error message here')
    return message

Note that the ValidationError will return a 400 Bad Request status code which is better for when a required field is missing from the POST data

Upvotes: 4

Related Questions