GraphQL Client Typed Queries
Execute typed GraphQL queries with graphql-client crate in Rust for type-safe fetching.
Code
use graphql_client::GraphQLQuery;
use serde::Serialize;
#[derive(GraphQLQuery)]
#[graphql(query_path = "queries.graphql", schema_path = "schema.graphql")]
struct GetUsers;
#[derive(Serialize)]
struct Variables {
limit: i32,
}
async fn fetch_users(endpoint: &str, vars: Variables) -> Result<GetUsers::ResponseData, Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let res = client.post(endpoint).json(&GetUsers::build(vars)).send().await?.json().await?;
Ok(res)
}What the code does
GraphQL Client Typed Queries comes down to the function fetch_users.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Points of care
- Plan for an install step:
graphql_client::GraphQLQueryandserde::Serializeare a real dependency, resolved by the package manager. - Every fallible call yields a
Resultyou must unwrap or propagate; there is no implicit throw.
Applying it
The primary signature is fn fetch_users(endpoint: &str, vars: Variables) -> Result<GetUsers::ResponseData, Box<dyn std::error::Error>>
Import fetch_users from the file and call it — the rest of the code is implementation detail.
Statements that matter
async fn fetch_users(endpoint: &str, vars: Variables) -> Result<GetUsers::ResponseData, Box<dyn std::error::Error>> {
let client = reqwest::Client::new();
let res = client.post(endpoint).json(&GetUsers::build(vars)).send().await?.json().await?;
Ok(res)
}
Interactive Tools for This Topic
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.
FAQ
- What happens when a call fails?
- Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
- Does this require external packages?
- Yes — `graphql_client::GraphQLQuery` and `serde::Serialize`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.