GraphQL Client Typed Queries Rust
Execute GraphQL queries from Rust with graphql-client, deriving response types from the query document and variables.
Code
use graphql_client::{GraphQLQuery, Response};
// queries/top_customers.graphql:
// query TopCustomers($region: Region!, $first: Int!) {
// customers(region: $region, first: $first) {
// edges { node { id name lifetimeValue } }
// }
// }
#[derive(GraphQLQuery)]
#[graphql(
query_path = "queries/top_customers.graphql",
schema_path = "schemas/customer.graphql",
response_derives = "Debug"
)]
pub struct TopCustomers;
type Customer = top_customers::TopCustomersCustomersEdgesNode;
async fn fetch_top_customers(
region: &str,
first: i64,
) -> Result<Vec<Customer>, Box<dyn std::error::Error>> {
let variables = top_customers::Variables {
region: region.into(),
first,
};
let request_body = TopCustomers::build_query(variables);
let client = reqwest::Client::new();
let res = client
.post("https://api.example.com/graphql")
.json(&request_body)
.send()
.await?
.error_for_status()?;
let response_body: Response<top_customers::ResponseData> = res.json().await?;
let data = response_body
.data
.ok_or("query returned no data")?;
if let Some(errors) = response_body.errors {
for err in &errors {
eprintln!("graphql error: {:?}", err.message);
}
}
let customers: Vec<Customer> = data
.customers
.map(|conn| {
conn.edges
.into_iter()
.filter_map(|edge| edge.map(|e| e.node))
.collect()
})
.unwrap_or_default();
Ok(customers)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let customers = fetch_top_customers("eu", 5).await?;
for customer in customers {
println!("{:?} value={}", customer, customer.lifetime_value);
}
Ok(())
}Inside the snippet
GraphQL Client Typed Queries Rust keeps everything in the functions fetch_top_customers and main.
Repetition is confined to for err in &errors — the rest of the file is straight-line. Result is the error channel: the caller receives the failure as a value instead of an exception.
What to watch for
- Plan for an install step:
graphql_client::is a real dependency, resolved by the package manager. Resultis the only error channel — remove a?while adapting and that site needs an explicitmatch.
Using it
Signature: fn fetch_top_customers( region: &str, first: i64, ) -> Result<Vec<Customer>, Box<dyn std::error::Error>>
The sequence fetch_top_customers lives in main; running the file triggers it.
Key statements
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let customers = fetch_top_customers("eu", 5).await?;
for customer in customers {
println!("{:?} value={}", customer, customer.lifetime_value);
}
Ok(())
}
let response_body: Response<top_customers::ResponseData> = res.json().await?;
if let Some(errors) = response_body.errors {
for err in &errors {
eprintln!("graphql error: {:?}", err.message);
}
}
Interactive Tools for This Topic
GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.JSON to TypeScriptGenerate TypeScript interface and type declarations from a sample JSON payload, inferring primitives, arrays, and nested object shapes automatically.JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.
FAQ
- How does the code signal failure?
- No panics — `Result` values carry the failure, and `?` forwards them to the caller.
- Are there third-party dependencies?
- `graphql_client::` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.