GraphQL Client Typed Queries

Execute typed GraphQL queries with graphql-client crate in Rust for type-safe fetching.

RustData Fetching

Code

rustsnippet
17 lines
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::GraphQLQuery and serde::Serialize are a real dependency, resolved by the package manager.
  • Every fallible call yields a Result you 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

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.