user3808307
user3808307

Reputation: 1549

Understanding GraphQL

I started experimenting with the GraphQL wp api.

I am querying the menus. As for the documentation, the query is very long

I would expect that querying

{
    menus
}

only would bring about all the data nested in menus, it does not.

Why is this? What is the way to getting all nested data in an object as to see what's in there?

Thank you for your time

Upvotes: 1

Views: 355

Answers (3)

Andrew Ingram
Andrew Ingram

Reputation: 5220

If you keep in mind that you're getting back a JSON object, you can think of your GraphQL query as defining the left-hand side of the response (this is intentional in how it was designed), e.g. just the keys. So unless there are null values, what you get back should exactly match the shape of the query.

If you want to see what can be queried, you need access to the schema itself. If it's a schema provided by someone else (looks like WordPress in this case), they should also have provided the means to explore and understand it.

Upvotes: 2

Ken Chan
Ken Chan

Reputation: 90447

The rule is that every "leaf" fields in a GraphQL query should be a Scalar something like Int , Boolean , String etc. So if the meuns field in the root Query type is a Scalar , it is a valid query and will return you something.

If not , you have to continue navigating the Menu type and pick the fields that you want to include in the GraphQL query such as :

{
   menus {
     id
     createdDate
  }
}

There is no wildcard that can represent all fields in current GraphQL spec.You have to explicitly declare all fields you want to select in the query.By looking at the GraphQL schema, you can know the available fields for each type. One of the tips is to rely on the GraphQL introspection system .It basically means that you can use some of the GraphQL client such as Altair, Graphiql, or GraphQL Playground etc. which most of them will have some auto-suggest function that will guide you to compose a query by suggesting you what fields are available to be included for a type .

P.S. A similar analogy to SQL is that there is no select * from foo , you have to explicitly define the columns that you want to select in the select clause such as select id,name,address from foo.

Upvotes: 3

Max
Max

Reputation: 2036

That is the main feature of GraphQL, you can specify what data you need from a query. And because of that, you can't just query menus in that way, you need to specify every nested field in menus you need and only then it'll work :)

Upvotes: 1

Related Questions