1

I'm using strawberry-graphql in python, and have a query that returns a list of User

@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = get_from_database()
    return items

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

It works fine, but I want some additional attributes like total_item:

def get_user():
    items = get_from_database()
    return {
        'items': items
        'total_item': len(items)
    }

In above code, Strawberry converts the dict to a string, so It didn't work. I tried to create schemas:

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

But it says a query must return an iterable (Expected Iterable, but did not find one for field 'Query.allUser'.).

Is there any way around?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

2

Here's the fixed example:

from typing import List
import strawberry

@strawberry.type
class User:
    email: str
    name: str

def get_user():
    items = [User(email="email", name="Pat")]
    return GetUserResult(
        items=items,
        item_count=len(items)
    )

@strawberry.type
class User:
    email: str
    name: str

@strawberry.type
class GetUserResult:
    items: List[User]
    item_count: int

@strawberry.type
class Query:
    all_user: GetUserResult = strawberry.field(resolver=get_user)

schema = strawberry.Schema(Query)

you can test here too.

The issue was that in the second snippet you defined:

def get_user():
    items = get_from_database()
    return GetUserResult(
        items = items
        item_count = len(items)
    )

but the query was still expecting a List of users

@strawberry.type
class Query:
    all_user: List[User] = strawberry.field(resolver=get_user)

patrick
  • 6,533
  • 7
  • 45
  • 66