I want to add a GraphQL API to an application alongside its existing REST API. The application has an abstraction layer that defines all its commands and queries as data transfer objects (DTO) using Python dataclasses. I want to map these dataclasses into GraphQL types. I cannot change their definitions directly, as that would add a strawberry dependency into the core app.
So I have a situation that looks a lot like the experimental Pydantic integration.
# core/dtos.py
@dataclass
class AuthorDTO:
name: str
books: list['BookDTO']
@dataclass
class BookDTO:
title: str
author: AuthorDTO
Is there a supported way to register these as GraphQL types and add resolvers onto them?
For example, this is a perfectly working schema.py
:
# graphql/schema.py
def get_authors(root) -> list["Author"]:
return [Author(name="Michael Crichton")]
def get_author_for_book(root) -> "Author":
return Author(name="Michael Crichton")
def get_books_for_author(root):
return [Book(title="Jurassic Park")]
@strawberry.type
class Book:
title: str
author: "Author" = strawberry.field(resolver=get_author_for_book)
@strawberry.type
class Author:
name: str
books: list[Book] = strawberry.field(resolver=get_books_for_author)
@strawberry.type
class Query:
authors: list[Author] = strawberry.field(resolver=get_authors)
books: list[Book] = strawberry.field(resolver=get_books_for_author)
but what I want instead is to define Book
and Author
maybe like this:
class Book(strawberry.type(BookDTO)):
author: "Author" = strawberry.field(resolver=get_author_for_book)
class Author(strawberry.type(AuthorDTO)):
books: list[Book] = strawberry.field(resolver=get_books_for_author)
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too