BaconCandy
BaconCandy

Reputation: 11

Query GraphQL with a list of values

Trying to query a list of Employee objects by providing a list of emp_codes but feeling like I am missing something in my following GraphQL query.

Also tried looking into this emp_code__in=emp_codes without luck.

I appreciate your insights since I am fairly new to GraphQL

emp_codes_list = ['1', '2', '3']
# Expecting to return: [{empCode: '1', firstName: 'J', lastName: S'}, {empCode: '2', firstName: 'T', lastName: S'}, {empCode: '3', firstName: 'A', lastName: B'}]

    query() = f"""
      {{
        profileEmpCode(empCode:"{emp_codes_list}") {{
          ... on Employeelist {{
            Employeelist {{
              firstName
              lastName
              empCode
            }}
          }}
          ... on AuthInfoField {{
            message
          }}
        }}
      }}
    """

Upvotes: 0

Views: 994

Answers (2)

Denis Artyushin
Denis Artyushin

Reputation: 374

This may be helpful to viewers.

You can using graphql-query package as best way for GraphQL query string generation in python:

from graphql_query import Argument, InlineFragment, Field, Operation, Query

arg_emp_code = Argument(name="empCode", value=['"1"', '"2"', '"3"'])

profile_emp_code = Query(
    name="profileEmpCode",
    arguments=[arg_emp_code],
    fields=[
        InlineFragment(
            type="Employeelist",
            fields=[
                Field(name="Employeelist", fields=["firstName", "lastName", "empCode"])
            ]
        ),
        InlineFragment(type="AuthInfoField", fields=["message"]),
    ]
)
operation = Operation(type="query", queries=[profile_emp_code])

print(operation.render())
"""
query {
  profileEmpCode(
    empCode: ["1", "2", "3"]
  ) {
    ... on Employeelist {
      Employeelist {
        firstName
        lastName
        empCode
      }
    }
    ... on AuthInfoField {
      message
    }
  }
}
"""

Upvotes: 0

Philip Tzou
Philip Tzou

Reputation: 6438

"{emp_codes_list}" passes a string but not a list to the GraphQL server.

import json
emp_codes_list = json.dumps(['1', '2', '3'])
# Expecting to return: [{empCode: '1', firstName: 'J', lastName: S'}, {empCode: '2', firstName: 'T', lastName: S'}, {empCode: '3', firstName: 'A', lastName: B'}]

query() = f"""
  {{
    profileEmpCode(empCode:{emp_codes_list}) {{
      ... on Employeelist {{
        Employeelist {{
          firstName
          lastName
          empCode
        }}
      }}
      ... on AuthInfoField {{
        message
      }}
    }}
  }}
"""

Upvotes: 1

Related Questions