'Get a list of entities by list of ids in GraphQL

Let's say I have the following schema:

type Query {
  user(id: ID!): User
}

type User {
  name: String!
  id: ID!
}

If I want to create a query to get user by id, I can easily do that like so:

query UserById($id: ID!) {
    user(id: $id) {
        name
        id
    }
}

But what if I have a list of ids and I want to get a list / map of users corresponding to this list of ids?

According to the GraphQL specification, it's not recommended to build a query dynamically, so I'd prefer an answer that uses a hard coded query, and enables passing the list of ids as a variable.



Solution 1:[1]

You can use the allUsers insted of the UserById, and provide the list as a filter.

query MyQuery {
  allUsers(filter: {id: {in: ""}}) {
    nodes {
      id
      name
    }
  }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 barianos