Django graphene mutation input validation

Snippet

import graphene

class ScratchpadMutation(graphene.relay.ClientIDMutation):
    class Input:
        created_by = graphene.String(required=True)
        foobar = graphene.String()

    test = graphene.String()
    test2 = graphene.String()

    @classmethod
    def validate_created_by(cls, value: str) -> str:
        if "foo" in value:
            raise ValueError("No foo's allowed")
        return value.strip().upper()

    @classmethod
    def validate_combinations(cls, input: dict) -> dict:
        if input.get("created_by") == "TEST" and input.get("foobar") == "TEST":
            raise ValueError("Cannot have both created_by and foobar as TEST")

        return input

    @classmethod
    def validate_inputs(cls, input: dict) -> dict:
        validated_inputs = input.copy()
        for key, value in input.items():
            validation_method = f"validate_{key}"
            # Check if the method exists and run if so
            if hasattr(cls, validation_method):
                method = getattr(cls, validation_method)
                validated_inputs[key] = method(value)

        # Run other validations on all the inputs after the pre-validate/cleaning
        validated_inputs = cls.validate_combinations(validated_inputs)

        return validated_inputs

    @classmethod
    def mutate_and_get_payload(cls, root, info, **input):
        # Need to update since not all fields may have a validation method
        input = cls.validate_inputs(input)
        
        # do somthing with the inputs here
        
        return ScratchpadMutation(
            test=input.get("created_by"), test2=input.get("foobar")
        )

Description

This is an example on how one could implement additional validation for django graphene mutation inputs. This can clean and validate input values beyond the graphene types that are set in the Input class

By xtream1101 Updated 2025-02-06 14:13