Docs
General
Types
Codegen
Extensions
>Errors
>Guides
Editor integration
Concepts
Integrations
Federation
Operations
Input types
In addition to object types GraphQL also supports input types. While being similar to object types, they are better suited for input data as they limit the kind of types you can use for fields.
This is how the GraphQL spec defines the difference between object types and input types:
The GraphQL Object type (ObjectTypeDefinition)... is inappropriate for reβuse (as input), because Object types can contain fields that define arguments or contain references to interfaces and unions, neither of which is appropriate for use as an input argument. For this reason, input objects have a separate type in the system.
Defining input types
In Strawberry, you can define input types by using the @strawberry.input
decorator, like this:
import strawberry
@strawberry.inputclass Point2D: x: float y: float
input Point2D { x: Float! y: Float!}
Then you can use input types as argument for your fields or mutations:
import strawberry
@strawberry.typeclass Mutation: @strawberry.mutation def store_point(self, a: Point2D) -> bool: return True
If you want to include optional arguments, you need to provide them with a default. For example if we want to expand on the above example to allow optional labeling of our point we could do:
import strawberryfrom typing import Optional
@strawberry.inputclass Point2D: x: float y: float label: Optional[str] = None
type Point2D { x: Float! y: Float! label: String = null}
Alternatively you can also use strawberry.UNSET
instead of the None
default
value, which will make the field optional in the schema:
import strawberryfrom typing import Optional
@strawberry.inputclass Point2D: x: float y: float label: Optional[str] = strawberry.UNSET
type Point2D { x: Float! y: Float! label: String}
API
@strawberry.input(name: str = None, description: str = None)
Creates an input type from a class definition.
name
: if set this will be the GraphQL name, otherwise the GraphQL will be generated by camel-casing the name of the class.description
: this is the GraphQL description that will be returned when introspecting the schema or when navigating the schema using GraphiQL.