BudiBadu Logo
Samplebadu

GraphQL by Example: Query Operations

June 2018 Specification

Fetching data from GraphQL APIs with this sample code demonstrating query operation syntax, field selection for precise data requirements, response structure matching query shape, and shorthand versus explicit query keyword usage.

Code

# The 'query' keyword is optional for simple queries
# but it is good practice to include it.
query {
  # We are asking for the 'hello' field
  hello
}

# Response:
# {
#   "data": {
#     "hello": "world"
#   }
# }

Explanation

GraphQL query operations define what data clients want to retrieve from servers, addressing over-fetching and under-fetching problems prevalent in REST APIs. Unlike REST endpoints returning fixed data structures, GraphQL requires clients to explicitly list every field they need, ensuring only requested data is transferred. The server responds with JSON matching the exact shape of the query, providing predictable results.

Query operations use the query keyword followed by a selection set in curly braces containing the fields to fetch. While the query keyword and operation name are optional for simple queries using shorthand syntax, including them in production applications aids debugging, logging, and enables variable passing. The response always contains a data key holding the requested fields and their values.

GraphQL execution begins at root Query fields, with the execution engine traversing the schema following the query structure and resolving each requested field. When a field is executed, its corresponding resolver function is called to produce the next value. This granular control eliminates over-fetching by returning only specified fields, directly solving the problem of receiving unnecessary data common in REST APIs.

Code Breakdown

3
query { ... } defines operation type, alternatives include mutation and subscription.
5
hello field selection, server executes resolver function to get value.
9-12
Response structure mirrors query shape with data key containing results.
1-2
Comments explain shorthand syntax, query keyword optional for simple operations.