21

Say I have the following json data:

"data": {
    "continents": [
        {
            "code": "AF",
            "name": "Africa",
        },
        {
            "code": "EU",
            "name": "Europe"
        },
        // ...
    ]
}

What would be the correct GraphQL query to fetch a list item with: code : "AF"? In other words, how to produce the following result:

"data": {
    "code": "AF",
    "name": "Africa"
}

So far, I have:

query {
  continents {
    code
    name
  }
}

but that simply returns the full array.

I've been running my examples on: https://lucasconstantino.github.io/graphiql-online/

2 Answers 2

24

As it turns out, there is no built-in filter function defined on lists/arrays! GraphQL (query language) is basically about selecting fields on objects [Schemas and Types | GraphQL].

One only needs to look at the GraphQL schema in question:

type Query {
  continents(filter: ContinentFilterInput): [Continent!]!
  // ...
}
type Continent {
  code: ID!
  name: String!
  countries: [Country!]!
}
input ContinentFilterInput {
  code: StringQueryOperatorInput
}
input StringQueryOperatorInput {
  eq: String
  ne: String
  in: [String]
  nin: [String]
  regex: String
  glob: String
}
// ...

We see that query continents has a parameter filter of input type ContinentFilterInput. That's enough information for us to start building our filter query:

query {
  continents(filter: ...) {
    code
    name
  }
}

Upon inspecting ContinentFilterInput, we observe that it has a single field code of input type StringQueryOperatorInput:

query {
  continents(filter: { code: ...}) {
    code
    name
  }
}

Finally, we find a field eq inside input type StringQueryOperatorInput which is a scalar type (String) and we are done:

query {
  continents(filter: { code: { eq: "AF" } }) {
    code
    name
  }
}
11

For this current example you can just do

query {
  continents(filter: {code: {eq: "AF"}}) {
    name
  }
}

I'd suggest to review the documentation regarding arguments since they explain it quite well.

2
  • 1
    Wait a minute, I am not using any variables. And I could find no mention of filter nor eq in the docs. That said, your query somewhat answers my question. Jan 23, 2021 at 21:58
  • corrected my answer, hope this clarifies, arguments is what is used here, mixed those two up. there is a filter argument that is passed in the graphql function and in the backend dal they use this argument to filter
    – Noam
    Jan 23, 2021 at 23:48

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.