# POST data validation in DjangoRestFramework API

**URL:** <https://forum.djangoproject.com/t/post-data-validation-in-djangorestframework-api/22460>\
**Category:** Forms & APIs\
**Created:** [July 21, 2023, 4:17pm UTC](https://forum.djangoproject.com/t/post-data-validation-in-djangorestframework-api/22460 "2023-07-21T16:17:24Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![xaleel](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/xaleel/32/14920_2.png) [@xaleel](https://forum.djangoproject.com/u/xaleel)\
**Post date:** [July 21, 2023, 4:17pm UTC](https://forum.djangoproject.com/t/post-data-validation-in-djangorestframework-api/22460/1 "2023-07-21T16:17:24Z")

</div>

I have the following to validate data from POST requests and I wanted to ask whether this follows best practices for Python, Django, OOP, and DRF. Any advice is highly appreciated 🙂

`urls.py` and `views.py` are similar to most apps.

```auto
# ---- models.py ---- #

class User(AbstractUser):
    ...
    phone_number = models.CharField(max_length=20, null=True)
    email = models.EmailField(unique=True, null=True)

# ---- serializers.py ---- #

from .models import *
from rest_framework import serializers
from .validator import Validator

class GenericSerializer(Validator, serializers.HyperlinkedModelSerializer):
    ...
    def validate(self, data: dict) -> dict:
        return super().validate(data)

class UserSerializer(GenericSerializer):
    class Meta:
        model = User
        fields = [
            "email",
            "phone_number",
            ...
        ]

# ---- validator.py ---- #

from rest_framework.serializers import ValidationError

class Validator:
    def validate(self, data: dict) -> dict:
        match self. __class__. __name__ :
            case "UserSerializer":
                return self.validate_user(data)
            ...
        return data

    def validate_user(self, data: dict) -> dict:
        if not (data["email"] or data["phone_number"]):
            raise ValidationError(
                {
                    "email": "Must provide either email or phone number",
                    "phone_number": "Must provide either email or phone number",
                }
            )
        return data
    ...

```
