Maybe Field Error

Description

This error is thrown when a field of a @strawberry.pydantic.input uses strawberry.Maybe in a way the integration doesn’t support:

A Maybe field on a @strawberry.pydantic.type or @strawberry.pydantic.interface raises a MaybeFieldOnOutputTypeError instead, as Maybe is for inputs.

For example, the following code throws this error:

import pydantic
import strawberry
@strawberry.pydantic.input
class UpdateUserInput(pydantic.BaseModel):
name: strawberry.Maybe[str] = "Ada"

How to fix this error

Remove the default: a Maybe field is None when the client leaves it out, and a strawberry.Some with the value when it sends one. Pydantic validates the value inside the Some , and doesn’t validate the None the field gets when it’s left out.

import pydantic
import strawberry
@strawberry.pydantic.input
class UpdateUserInput(pydantic.BaseModel):
name: strawberry.Maybe[str]
@strawberry.type
class Mutation:
@strawberry.mutation
def update_user(self, input: UpdateUserInput) -> str:
if input.name is None:
return "Name was omitted"
return f"Name was supplied: {input.name.value!r}"

Put constraints and validators in the type inside the Maybe , where they apply to the value. A @field_validator with mode="before" or mode="wrap" works too, as it gets the value the client sent:

from typing import Annotated
import pydantic
import strawberry
def check_name(name: str) -> str:
return name.strip()
@strawberry.pydantic.input
class UpdateUserInput(pydantic.BaseModel):
age: strawberry.Maybe[Annotated[int, pydantic.Field(ge=0)]]
name: strawberry.Maybe[Annotated[str, pydantic.AfterValidator(check_name)]]

Contributors:

Edit this page on GitHub