graphql
stableBuild GraphQL query, mutation, subscription, and fragment strings, and parse or inspect JSON responses.
use plugin graphql::{query, mutation, build_request, …} Functions (11)
- query Build a query operation string
- mutation Build a mutation operation string
- build_request Serialize query + variables to JSON
- parse_response Parse JSON response into data and errors
- extract_errors Extract the errors array from a response
- has_errors Check if a response contains errors
- subscription Build a subscription operation string
- fragment Build a named fragment string
- introspection_query Return the standard introspection query
- build_request_with_operation Serialize query with variables and operationName
- extract_data Extract just the data field from a response
Overview
graphql is a stringly-typed helper for assembling GraphQL requests and dissecting
their responses without pulling in a full client library. The builder functions
(query, mutation, subscription, fragment) take operation names and raw
selection-set text and stitch them into a valid operation string, while
build_request and build_request_with_operation wrap a query plus a variables
table into the JSON envelope a GraphQL endpoint expects. There is no connection or
session object — every function is pure: text and tables go in, strings or tables
come out, so you stay in control of how the request is actually sent (typically via
the http plugin).
On the response side, parse_response, extract_data, extract_errors, and
has_errors turn a raw JSON response string into ordinary Zolo tables so you can
read data and errors with normal indexing. Reach for this plugin whenever you
want to talk to a GraphQL API but prefer to own the transport yourself.
Common patterns
Build a query, wrap it in a request body, then read the data back out of the response:
use plugin graphql::{query, build_request, parse_response}
let q = query("GetUser", "user(id: $id) { name email }")
let body = build_request(q, #{"id": 42})
print("request body: {body}")
let resp = parse_response('{"data":{"user":{"name":"Alice","email":"[email protected]"}}}')
print("name: {resp["data"]["user"]["name"]}")
Guard against failures before trusting the payload:
use plugin graphql::{has_errors, extract_errors, extract_data}
let raw = '{"data":null,"errors":[{"message":"not found"}]}'
if has_errors(raw) {
let errs = extract_errors(raw)
print("failed: {errs[0]["message"]}")
} else {
print(extract_data(raw))
}
Define a reusable fragment and spread it into a mutation's selection set:
use plugin graphql::{fragment, mutation}
let f = fragment("UserFields", "User", "id name email")
let m = mutation("CreateUser", "$name: String!", "createUser(name: $name) { ...UserFields }")
print(f)
print(m)
Build a query operation string
Builds a GraphQL query string. Pass an empty string for operation_name to produce an anonymous query.
use plugin graphql::{query}
let q = query("GetUser", "user(id: 1) { name email }")
print(q)
Passing an empty operation name yields a shorthand anonymous query ({ ... }):
use plugin graphql::{query}
print(query("", "viewer { id }"))
Build a mutation operation string
Builds a GraphQL mutation string. Pass an empty string for variables_str to omit variable declarations.
use plugin graphql::{mutation}
let m = mutation("CreateUser", "$name: String!", "createUser(name: $name) { id }")
print(m)
With no variable declarations the operation has no parameter list:
use plugin graphql::{mutation}
print(mutation("Ping", "", "ping { ok }"))
Serialize query + variables to JSON
Serializes a GraphQL query string and optional variables table into a JSON string suitable for an HTTP request body.
use plugin graphql::{query, build_request}
let q = query("GetUser", "user(id: $id) { name }")
let body = build_request(q, #{"id": 42})
print(body)
Pass nil for the variables when the query takes no arguments — the variables
key is then omitted entirely:
use plugin graphql::{query, build_request}
let q = query("Health", "health { status }")
print(build_request(q, nil))
Parse JSON response into data and errors
Parses a GraphQL JSON response string and returns a table with data and errors fields as Zolo values.
use plugin graphql::{parse_response}
let resp = parse_response('{"data":{"user":{"name":"Alice"}},"errors":null}')
print(resp["data"]["user"]["name"])
The returned table always has both keys, so you can branch on errors directly:
use plugin graphql::{parse_response}
let resp = parse_response('{"data":null,"errors":[{"message":"boom"}]}')
if resp["errors"] != nil {
print("first error: {resp["errors"][0]["message"]}")
}
Extract the errors array from a response
Extracts just the errors array from a raw GraphQL JSON response string. Returns an empty table if no errors are present.
use plugin graphql::{extract_errors}
let errs = extract_errors('{"data":null,"errors":[{"message":"not found"}]}')
print(errs[0]["message"])
Check if a response contains errors
Returns true if the GraphQL JSON response contains a non-empty errors field.
use plugin graphql::{has_errors}
let raw = '{"data":null,"errors":[{"message":"unauthorized"}]}'
if has_errors(raw) {
print("request failed")
}
Build a subscription operation string
Builds a GraphQL subscription operation string.
use plugin graphql::{subscription}
let s = subscription("OnMessage", "messageAdded { id text author }")
print(s)
An empty operation name produces an anonymous subscription:
use plugin graphql::{subscription}
print(subscription("", "ticks { value }"))
Build a named fragment string
Builds a named GraphQL fragment string for reuse across multiple operations.
use plugin graphql::{fragment}
let f = fragment("UserFields", "User", "id name email createdAt")
print(f)
Return the standard introspection query
Returns the standard GraphQL introspection query string. Use it to fetch full schema information from any GraphQL endpoint.
use plugin graphql::{introspection_query, build_request}
let q = introspection_query()
let body = build_request(q, nil)
print(body.len())
Serialize query with variables and operationName
Like build_request, but also includes an operationName field in the JSON payload when provided.
use plugin graphql::{query, build_request_with_operation}
let q = query("GetUser", "user(id: $id) { name }")
let body = build_request_with_operation(q, #{"id": 1}, "GetUser")
print(body)
Extract just the data field from a response
Extracts just the data field from a GraphQL JSON response. Returns nil if the field is absent.
use plugin graphql::{extract_data}
let raw = '{"data":{"items":[1,2,3]}}'
let data = extract_data(raw)
print(data["items"][0])
Pair it with has_errors to only unwrap the payload on success:
use plugin graphql::{has_errors, extract_data}
let raw = '{"data":{"count":7}}'
if !has_errors(raw) {
print("count: {extract_data(raw)["count"]}")
}