To use graphql_client, you need a GraphQL schema (in .graphql or .json format) and a .graphql file containing your query. The library uses a procedural macro to generate typed Rust structures at compile-time.
- Save your query in a
.graphql file. - Download your schema (you can use the provided
graphql_client_cli). - Use the
#[derive(GraphQLQuery)] macro on a struct to generate the necessary types.
The macro generates a module named after your struct (in snake case). This module contains:
ResponseData: The root type for the response.Variables: A struct representing the expected query variables.
To send a request, use the GraphQLQuery::build_query(variables) method to create the request payload.
use graphql_client::{GraphQLQuery, Response};
use std::error::Error;
use reqwest;
#[derive(GraphQLQuery)]
#[graphql(
schema_path = "tests/unions/union_schema.graphql",
query_path = "tests/unions/union_query.graphql",
response_derives = "Debug",
)]
pub struct UnionQuery;
async fn perform_my_query(variables: union_query::Variables) -> Result<(), Box<dyn Error>> {
// this is the important line
let request_body = UnionQuery::build_query(variables);
let client = reqwest::Client::new();
let mut res = client.post("/graphql").json(&request_body).send().await?;
let response_body: Response<union_query::ResponseData> = res.json().await?;
println!("{:#?}", response_body);
Ok(())
}