GraphQL by Example: Query Operations
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
query { ... } defines operation type, alternatives include mutation and subscription.hello field selection, server executes resolver function to get value.
