Strawberry supports using Pythonβs Generic typing to dynamically create
reusable types.
Strawberry will automatically generate the correct GraphQL schema from the
combination of the generic type and the type arguments. Generics are supported
in Object types, Input types, and Arguments to queries, mutations, and scalars.
Letβs take a look at an example:
Object Types
from typing import Generic, List, TypeVar
import strawberry
T = TypeVar("T")
@strawberry.type
classPage(Generic[T]):
number: int
items: List[T]
This example defines a generic type Page that can be used to represent a page
of any type. For example, we can create a page of User objects:
import strawberry
@strawberry.type
classUser:
name: str
@strawberry.type
classQuery:
users: Page[User]
typeQuery {
users: UserPage!
}
typeUser {
name: String!
}
typeUserPage {
number: Int!
items: [User!]!
}
It is also possible to use a specialized generic type directly. For example, the
same example above could be written like this:
import strawberry
@strawberry.type
classUser:
name: str
@strawberry.type
classUserPage(Page[User]): ...
@strawberry.type
classQuery:
users: UserPage
typeQuery {
users: UserPage!
}
typeUser {
name: String!
}
typeUserPage {
number: Int!
items: [User!]!
}
Input and Argument Types
Arguments to queries and mutations can also be made generic by creating Generic
Input types. Here weβll define an input type that can serve as a collection of
anything, then create a specialization by using as a filled-in argument on a
mutation.
import strawberry
from typing import Generic, List, Optional, TypeVar
Note: Pay attention to the fact that both CollectionInput and
PostInput are Input types. Providing posts: CollectionInput[Post] to
add_posts (i.e. using the non-input Post type) would have resulted in an
error:
PostCollectionInput fields cannot be resolved. Input field type must be a
GraphQL input type
Multiple Specializations
Using multiple specializations of a Generic type will work as expected. Here we
define a Point2D type and then specialize it for both int s and float s.