### Install graphql-client CLI Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Install the graphql-client CLI using Cargo. The --force flag is used to overwrite any existing installation. ```bash cargo install graphql_client_cli --force ``` -------------------------------- ### Run GitHub API Example Source: https://github.com/graphql-rust/graphql-client/blob/main/examples/github/README.md Execute the example with a repository name as an argument. Ensure the GITHUB_API_TOKEN environment variable is set. ```bash cargo run --example github graphql-rust/graphql-client ``` -------------------------------- ### Install graphql-client CLI Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Installs the graphql-client CLI using Cargo. The --force flag is used to overwrite any existing installation. ```APIDOC ## Install ```bash car go install graphql_client_cli --force ``` ``` -------------------------------- ### Install Prettier for JSON/GraphQL Formatting Source: https://github.com/graphql-rust/graphql-client/blob/main/CONTRIBUTING.md Install Prettier globally using npm to format .json and .graphql files. Node.js must be installed first. ```bash npm install --global prettier ``` -------------------------------- ### Install graphql-client CLI for Formatting Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Install the graphql-client CLI using Cargo. This command is specifically mentioned for enabling the formatting feature. ```bash cargo install graphql_client_cli ``` -------------------------------- ### Serve Project with HTTP Server Source: https://github.com/graphql-rust/graphql-client/blob/main/examples/web/README.md Start a simple HTTP server to serve the project files, including the compiled WebAssembly and HTML, for browser access. Requires Python 3. ```bash python3 -m http.server 8000 ``` -------------------------------- ### Add Rustfmt and Clippy Components Source: https://github.com/graphql-rust/graphql-client/blob/main/CONTRIBUTING.md Install rustfmt and clippy components for local testing. These tools check code formatting and linting. ```bash rustup component add rustfmt-preview clippy-preview ``` ```bash rustup component add rustfmt-preview clippy-preview --toolchain stable ``` -------------------------------- ### Introspect GraphQL Schema Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Command to get the schema from a live GraphQL API. The schema is printed to stdout. Use --no-ssl to disable SSL certificate verification. ```bash graphql-client introspect-schema ``` -------------------------------- ### Construct Nested Input Objects for GraphQL Mutations Source: https://context7.com/graphql-rust/graphql-client/llms.txt Define complex input types as nested Rust structs. This example demonstrates creating a `SendMessage` mutation with nested `MessageInput` and `RecipientInput` structs, which are then passed as variables to the query builder. ```rust use graphql_client::GraphQLQuery; // schema.graphql: // input MessageInput { // content: String // recipient: RecipientInput! // } // input RecipientInput { // email: String! // name: String // } #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "mutation.graphql", response_derives = "Debug" )] pub struct SendMessage; fn main() { // Construct nested input objects let variables = send_message::Variables { message: Some(send_message::MessageInput { content: Some("Hello, World!".to_string()), recipient: send_message::RecipientInput { email: "alice@example.com".to_string(), name: Some("Alice".to_string()), }, }), }; let query = SendMessage::build_query(variables); let json = serde_json::to_string_pretty(&query).unwrap(); println!("{}", json); // { // "operationName": "SendMessage", // "query": "mutation SendMessage...", // "variables": { // "message": { // "content": "Hello, World!", // "recipient": { // "email": "alice@example.com", // "name": "Alice" // } // } // } // } } ``` -------------------------------- ### Custom Scalars in GraphQL Schemas Source: https://context7.com/graphql-rust/graphql-client/llms.txt Map custom GraphQL scalar types to Rust types using type aliases. This example demonstrates mapping a custom scalar to `std::net::Ipv4Addr` and other simple scalars to `String` and `serde_json::Value`. ```rust use graphql_client::GraphQLQuery; use std::net::Ipv4Addr; use serde_json::json; // Map custom scalar to standard library type type NetworkAddress = Ipv4Addr; // Or use type aliases for simple scalars type DateTime = String; type JSON = serde_json::Value; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql" )] pub struct NetworkQuery; fn main() { let response_json = json!({ "serverAddress": "192.168.1.1", "lastUpdated": "2024-01-15T10:30:00Z" }); let data: network_query::ResponseData = serde_json::from_value(response_json).unwrap(); // Custom scalar deserializes to Ipv4Addr assert_eq!(data.server_address.unwrap(), Ipv4Addr::new(192, 168, 1, 1)); } ``` -------------------------------- ### Handle GraphQL Union Types in Rust Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use Rust enums to represent GraphQL unions. Each enum variant corresponds to a possible type in the union, with associated structs for type-specific fields. This example shows how to process a union response by matching on the `__typename`. ```rust use graphql_client::GraphQLQuery; use serde_json::json; // schema.graphql: // union SearchResult = User | Repository | Issue // // query.graphql: // query Search($term: String!) { // search(term: $term) { // __typename // ... on User { username } // ... on Repository { name stars } // ... on Issue { title state } // } // } #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", response_derives = "Debug" )] pub struct Search; fn main() { let response = json!({ "search": [ { "__typename": "User", "username": "alice" }, { "__typename": "Repository", "name": "graphql-client", "stars": 1000 }, { "__typename": "Issue", "title": "Bug report", "state": "OPEN" } ] }); let data: search::ResponseData = serde_json::from_value(response).unwrap(); for result in data.search.unwrap() { match result.on { search::SearchOn::User(user) => { println!("User: {}", user.username); } search::SearchOn::Repository(repo) => { println!("Repo: {} ({} stars)", repo.name, repo.stars); } search::SearchOn::Issue(issue) => { println!("Issue: {} [{}]", issue.title, issue.state); } } } } ``` -------------------------------- ### CLI: Generate Rust Code from GraphQL Queries Source: https://context7.com/graphql-rust/graphql-client/llms.txt Generate Rust modules from GraphQL queries using the `graphql-client` CLI, avoiding the need for the derive macro. Supports various options for customization. ```bash # Generate code for a single query graphql-client generate \ --schema-path schema.graphql \ --output-directory src/generated \ queries/get_user.graphql # With additional derives and options graphql-client generate \ --schema-path schema.json \ --output-directory src/graphql \ --response-derives "Debug, Clone, PartialEq" \ --variables-derives "Default" \ --deprecation-strategy warn \ --module-visibility pub \ queries/operations.graphql # Generate specific operation from multi-operation file graphql-client generate \ --schema-path schema.graphql \ --selected-operation GetUser \ --output-directory src/generated \ queries/all_operations.graphql # With custom scalars module graphql-client generate \ --schema-path schema.graphql \ --custom-scalars-module "crate::scalars" \ --output-directory src/generated \ queries/query.graphql # With external enums graphql-client generate \ --schema-path schema.graphql \ --external-enums Direction DistanceUnit \ --output-directory src/generated \ queries/navigation.graphql ``` -------------------------------- ### CLI: Introspect GraphQL Schema Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use the `graphql-client` CLI to introspect GraphQL APIs and download schemas. Supports custom headers, authentication, and disabling SSL verification. ```bash # Install the CLI carqo install graphql_client_cli # Introspect a GraphQL endpoint and save schema graphql-client introspect-schema https://api.example.com/graphql \ --output schema.json # With authentication header graphql-client introspect-schema https://api.github.com/graphql \ --output github_schema.json \ --authorization "Bearer $GITHUB_TOKEN" # With custom headers graphql-client introspect-schema https://api.example.com/graphql \ --output schema.json \ --header "X-API-Key: secret123" \ --header "X-Client-Version: 1.0" # Disable SSL verification (for development) graphql-client introspect-schema https://localhost:8080/graphql \ --output schema.json \ --no-ssl # Enable oneOf directive support graphql-client introspect-schema https://api.example.com/graphql \ --output schema.json \ --is-one-of ``` -------------------------------- ### Generate GraphQL Client Code Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Command to generate Rust client code from a GraphQL query file and schema. Use --no-formatting to skip rustfmt execution on the generated code. ```bash graphql-client generate [FLAGS] [OPTIONS] --schema-path ``` -------------------------------- ### Build WebAssembly Project Source: https://github.com/graphql-rust/graphql-client/blob/main/examples/web/README.md Use wasm-pack to build the Rust project for the web target. This generates the necessary WebAssembly binary and JavaScript glue code. ```bash wasm-pack build --target=web ``` -------------------------------- ### Async HTTP Client with reqwest Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use this function for making asynchronous GraphQL requests with reqwest. Ensure the `reqwest` or `reqwest-rustls` feature is enabled. Requires setting up a reqwest Client with necessary headers. ```rust use graphql_client::{GraphQLQuery, reqwest::post_graphql}; use reqwest::Client; type URI = String; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "repo_view.graphql", response_derives = "Debug" )] pub struct RepoView; #[tokio::main] async fn main() -> Result<(), Box> { let client = Client::builder() .user_agent("graphql-rust/0.16.0") .default_headers({ let mut headers = reqwest::header::HeaderMap::new(); headers.insert( reqwest::header::AUTHORIZATION, format!("Bearer {}", std::env::var("GITHUB_API_TOKEN")?).parse()?, ); headers }) .build()?; let variables = repo_view::Variables { owner: "graphql-rust".to_string(), name: "graphql-client".to_string(), }; let response = post_graphql::( &client, "https://api.github.com/graphql", variables, ).await?; if let Some(errors) = response.errors { for error in errors { eprintln!("GraphQL error: {}", error); } } if let Some(data) = response.data { let repo = data.repository.expect("repository exists"); println!("Stars: {}", repo.stargazers.total_count); } Ok(()) } ``` -------------------------------- ### Run Local Tests with Stable Toolchain Source: https://github.com/graphql-rust/graphql-client/blob/main/CONTRIBUTING.md Execute code formatting checks, linting, and unit tests locally using the stable Rust toolchain. ```bash cargo fmt --all -- --check ``` ```bash cargo clippy ``` ```bash cargo test --all ``` -------------------------------- ### Fetch GraphQL Data in WebAssembly Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use this function to perform GraphQL queries from a WebAssembly environment. It requires the `reqwest` feature to be enabled and `wasm-bindgen` for JavaScript interaction. Ensure your schema and query paths are correctly configured. ```rust use graphql_client::{GraphQLQuery, reqwest::post_graphql}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::future_to_promise; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.json", query_path = "src/query.graphql", response_derives = "Debug" )] struct FetchData; #[wasm_bindgen] pub fn fetch_data(id: String) -> js_sys::Promise { future_to_promise(async move { let client = reqwest::Client::new(); let variables = fetch_data::Variables { id }; let response = post_graphql::( &client, "https://api.example.com/graphql", variables, ) .await .map_err(|e| JsValue::from_str(&e.to_string()))?; match response.data { Some(data) => { let json = serde_json::to_string(&data) .map_err(|e| JsValue::from_str(&e.to_string()))?; Ok(JsValue::from_str(&json)) } None => Err(JsValue::from_str("No data returned")), } }) } ``` -------------------------------- ### Define Multiple Operations in a Single File Source: https://context7.com/graphql-rust/graphql-client/llms.txt Define multiple GraphQL operations (queries, mutations) in one file and select which one to generate by naming the struct. The struct name must match the operation name exactly. ```rust use graphql_client::GraphQLQuery; // operations.graphql contains multiple operations: // query GetUser($id: ID!) { user(id: $id) { name } } // query ListUsers { users { id name } } // mutation CreateUser($name: String!) { createUser(name: $name) { id } } // Struct name must match operation name exactly #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "operations.graphql" )] pub struct GetUser; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "operations.graphql" )] pub struct ListUsers; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "operations.graphql" )] pub struct CreateUser; fn main() { // Each generates its own module with appropriate types let get_vars = get_user::Variables { id: "123".into() }; let list_vars = list_users::Variables {}; let create_vars = create_user::Variables { name: "Alice".into() }; let _ = GetUser::build_query(get_vars); let _ = ListUsers::build_query(list_vars); let _ = CreateUser::build_query(create_vars); } ``` -------------------------------- ### Build and Send GraphQL Request Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Build a complete GraphQL request payload using the `build_query` method from the `GraphQLQuery` trait. Send the request using `reqwest` and deserialize the JSON response. ```rust 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> { // 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 = res.json().await?; println!("{:#?}", response_body); Ok(()) } ``` -------------------------------- ### GraphQL Subscription Support Source: https://context7.com/graphql-rust/graphql-client/llms.txt Subscriptions generate types similarly to queries and mutations. Use with WebSocket clients like `graphql-ws-client`. The subscription payload is built using the same format as queries. ```rust use graphql_client::GraphQLQuery; // subscription.graphql: // subscription OnNewMessage($roomId: ID!) { // newMessage(roomId: $roomId) { // id // content // author { name } // } // } #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "subscription.graphql", response_derives = "Debug" )] pub struct OnNewMessage; fn main() { let variables = on_new_message::Variables { room_id: "room-123".into(), }; // Build subscription payload (same format as queries) let subscription = OnNewMessage::build_query(variables); println!("Operation: {}", subscription.operation_name); println!("Query: {}", subscription.query); // Use with a WebSocket client like graphql-ws-client // let (sink, stream) = client.subscribe(subscription).await?; } ``` -------------------------------- ### Generate GraphQL Client Code Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Generates Rust client code from a GraphQL query file and schema. This allows for type-safe interaction with your GraphQL API. ```APIDOC ## generate client code USAGE: graphql-client generate [FLAGS] [OPTIONS] --schema-path FLAGS: -h, --help Prints help information --no-formatting If you don't want to execute rustfmt to generated code, set this option. Default value is false. -V, --version Prints version information OPTIONS: -I, --variables-derives Additional derives that will be added to the generated structs and enums for the variables. --variables-derives='Serialize,PartialEq' -O, --response-derives Additional derives that will be added to the generated structs and enums for the response. --response-derives='Serialize,PartialEq' -d, --deprecation-strategy You can choose deprecation strategy from allow, deny, or warn. Default value is warn. -m, --module-visibility You can choose module and target struct visibility from pub and private. Default value is pub. -o, --output-directory The directory in which the code will be generated -s, --schema-path Path to GraphQL schema file (.json or .graphql). -o, --selected-operation Name of target query. If you don't set this parameter, cli generate all queries in query file. --fragments-other-variant Generate an Unknown variant for enums generated by fragments. ARGS: Path to the GraphQL query file. ``` -------------------------------- ### Run Local Tests Forcing Stable Toolchain Source: https://github.com/graphql-rust/graphql-client/blob/main/CONTRIBUTING.md Force the use of the stable Rust toolchain to run code formatting checks, linting, and unit tests. ```bash cargo +stable fmt --all -- --check ``` ```bash cargo +stable clippy ``` ```bash cargo +stable test --all ``` -------------------------------- ### Derive GraphQLQuery Macro Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Use the `GraphQLQuery` derive macro to generate Rust types for your GraphQL queries. Specify schema and query file paths. The macro generates modules for response data and variables. ```rust use graphql_client::GraphQLQuery; // The paths are relative to the directory where your `Cargo.toml` is located. // Both json and the GraphQL schema language are supported as sources for the schema #[derive(GraphQLQuery)] #[graphql( schema_path = "tests/unions/union_schema.graphql", query_path = "tests/unions/union_query.graphql", )] pub struct UnionQuery; ``` -------------------------------- ### GraphQLQuery Derive Macro Usage Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use the `#[derive(GraphQLQuery)]` macro to generate typed Rust code for GraphQL queries. Specify schema and query file paths, and derive traits for variables and responses. The macro generates a module with `Variables`, `ResponseData`, and query constants. ```rust use graphql_client::GraphQLQuery; // Define custom scalar types used in your schema type URI = String; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", response_derives = "Debug, PartialEq", variables_derives = "Default", deprecated = "warn" )] pub struct MyQuery; // The macro generates a module named `my_query` containing: // - Variables struct for query inputs // - ResponseData struct for query outputs // - QUERY constant containing the query string // - OPERATION_NAME constant fn main() { // Construct variables with generated types let variables = my_query::Variables { owner: "graphql-rust".to_string(), name: "graphql-client".to_string(), }; // Build the request body let request_body = MyQuery::build_query(variables); // The body can be serialized to JSON for HTTP requests let json = serde_json::to_string(&request_body).unwrap(); println!("{}", json); // Output: {"operationName":"MyQuery","query":"query MyQuery...","variables":{"owner":"graphql-rust","name":"graphql-client"}} } ``` -------------------------------- ### Select Operations from Multi-Operation Documents Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Define multiple operations within a single GraphQL document and select a specific operation by naming the Rust struct the same as the operation. This allows for sharing fragments between operations. ```rust use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "tests/unions/union_schema.graphql", query_path = "tests/unions/union_query.graphql", )] pub struct Heights; ``` -------------------------------- ### Handle Deprecated Fields: Warn (Default) Source: https://context7.com/graphql-rust/graphql-client/llms.txt The default `deprecated = "warn"` setting includes deprecated fields and marks them with `#[deprecated]`. ```rust use graphql_client::GraphQLQuery; // deprecated = "warn" (default) - Fields marked with #[deprecated] #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", deprecated = "warn" )] pub struct WarnDeprecated; fn main() { // Deprecated fields are available but marked with #[deprecated] // Usage would typically involve a warning at compile time or runtime depending on compiler settings. } ``` -------------------------------- ### Handle Deprecated Fields in GraphQL Queries Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Configure how the generated Rust code handles deprecated fields in GraphQL schemas using the `deprecated` argument in the `GraphQLQuery` derive macro. The default value is `warn`. ```rust use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "tests/unions/union_schema.graphql", query_path = "tests/unions/union_query.graphql", deprecated = "warn" )] pub struct UnionQuery; ``` -------------------------------- ### Handle Deprecated Fields: Allow Source: https://context7.com/graphql-rust/graphql-client/llms.txt Configure the `deprecated` attribute to `allow` to include deprecated fields in generated types without warnings. ```rust use graphql_client::GraphQLQuery; // deprecated = "allow" - Fields are included without warnings #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", deprecated = "allow" )] pub struct AllowDeprecated; fn main() { // With "allow", use deprecated fields freely let _ = allow_deprecated::ResponseData { current_user: Some(allow_deprecated::AllowDeprecatedCurrentUser { id: Some("123".to_string()), name: Some("Alice".to_string()), // Deprecated fields available without warnings deprecated_field: Some("old value".to_string()), }), }; } ``` -------------------------------- ### Blocking HTTP Client with reqwest Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use this function for synchronous GraphQL requests with reqwest. Enable the `reqwest-blocking` feature. Requires building a blocking reqwest Client. ```rust use graphql_client::{GraphQLQuery, reqwest::post_graphql_blocking}; use reqwest::blocking::Client; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", response_derives = "Debug" )] pub struct GetUser; fn main() -> Result<(), Box> { let client = Client::builder() .user_agent("my-app/1.0") .timeout(std::time::Duration::from_secs(30)) .build()?; let variables = get_user::Variables { user_id: "user-123".to_string(), }; let response = post_graphql_blocking::( &client, "https://api.example.com/graphql", variables, )?; match (response.data, response.errors) { (Some(data), _) => println!("User: {:?}", data.user), (None, Some(errors)) => { for error in errors { eprintln!("Error: {}", error.message); } } (None, None) => eprintln!("Empty response"), } Ok(()) } ``` -------------------------------- ### Introspect GraphQL Schema Source: https://github.com/graphql-rust/graphql-client/blob/main/graphql_client_cli/README.md Retrieves the schema from a live GraphQL API and prints it to standard output as a JSON file. This can be useful for generating client code or for schema validation. ```APIDOC ## introspect schema Get the schema from a live GraphQL API. The schema is printed to stdout. USAGE: graphql-client introspect-schema [FLAGS] [OPTIONS] FLAGS: -h, --help Prints help information -V, --version Prints version information --no-ssl Set this option to disable ssl certificate verification. Default value is false. ssl verification is turned on by default. OPTIONS: --authorization Set the contents of the Authorization header. --header ... Specify custom headers. --header 'X-Name: Value' --output Where to write the JSON for the introspected schema. ARGS: The URL of a GraphQL endpoint to introspect. ``` -------------------------------- ### Skip Serializing None Values Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Configure the GraphQL derive macro to skip serializing None values. This is useful for omitting fields with null values from the GraphQL request. ```rust use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "tests/unions/union_schema.graphql", query_path = "tests/unions/union_query.graphql", skip_serializing_none )] struct UnionQuery; ``` -------------------------------- ### Handle Deprecated Fields: Deny Source: https://context7.com/graphql-rust/graphql-client/llms.txt Set `deprecated = "deny"` to exclude deprecated fields entirely from generated types, preventing their use. ```rust use graphql_client::GraphQLQuery; // deprecated = "deny" - Deprecated fields are excluded from generated types #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", deprecated = "deny" )] pub struct DenyDeprecated; fn main() { // With "deny", deprecated fields don't exist let _ = deny_deprecated::ResponseData { current_user: Some(deny_deprecated::DenyDeprecatedCurrentUser { id: Some("123".to_string()), name: Some("Alice".to_string()), // deprecated_field not generated - would be compile error }), }; } ``` -------------------------------- ### Skip Serializing None Values Source: https://context7.com/graphql-rust/graphql-client/llms.txt Use `skip_serializing_none` to omit null optional fields from the serialized request, supporting GraphQL's implicit null semantics. Only non-None values will be serialized. ```rust use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "mutation.graphql", skip_serializing_none )] pub struct UpdateUser; fn main() { // Only non-None values will be serialized let variables = update_user::Variables { user_id: "123".to_string(), name: Some("New Name".to_string()), email: None, // Won't appear in JSON bio: None, // Won't appear in JSON }; let query = UpdateUser::build_query(variables); let json = serde_json::to_string(&query.variables).unwrap(); // Only includes fields with values assert!(json.contains(r#"userId":"123"#)); assert!(json.contains(r#"name":"New Name"#)); assert!(!json.contains("email")); assert!(!json.contains("bio")); } ``` -------------------------------- ### Use External Enum Types Source: https://context7.com/graphql-rust/graphql-client/llms.txt Reference externally defined enum types using `extern_enums` in the `graphql` attribute. This is useful for sharing enums across multiple queries. Ensure enums have proper `serde` configuration. ```rust use graphql_client::GraphQLQuery; use serde::Deserialize; // Define enums externally with proper serde configuration #[derive(Deserialize, Debug, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum Direction { North, East, South, West, } #[derive(Deserialize, Debug, PartialEq, Eq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum DistanceUnit { Meter, Feet, Kilometer, } // Reference external enums in the derive #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", extern_enums("Direction", "DistanceUnit"), response_derives = "Debug, PartialEq" )] pub struct NavigationQuery; fn main() { use serde_json::json; let response = json!({ "distance": 100, "direction": "NORTH", "unit": "METER" }); let data: navigation_query::ResponseData = serde_json::from_value(response).unwrap(); // Uses external enum types assert_eq!(data.direction, Some(Direction::North)); assert_eq!(data.unit, DistanceUnit::Meter); } ``` -------------------------------- ### Derive Additional Traits on Response Source: https://github.com/graphql-rust/graphql-client/blob/main/README.md Customize the traits derived on the generated response types using the `response_derives` option in the `graphql` attribute. This allows for traits like `Serialize` or `PartialEq`. ```rust use graphql_client::GraphQLQuery; #[derive(GraphQLQuery)] #[graphql( schema_path = "tests/unions/union_schema.graphql", query_path = "tests/unions/union_query.graphql", response_derives = "Serialize,PartialEq", )] struct UnionQuery; ``` -------------------------------- ### Response Type Deserialization Source: https://context7.com/graphql-rust/graphql-client/llms.txt Deserialize GraphQL API responses using the `Response` struct. This struct handles the standard GraphQL response format, including data, errors, and extensions, and deserializes them into strongly-typed Rust structures. It supports both successful data and detailed error reporting. ```rust use graphql_client::{Response, Error, Location, PathFragment}; use serde::Deserialize; #[derive(Debug, Deserialize, PartialEq)] struct User { id: i32, name: String, } #[derive(Debug, Deserialize, PartialEq)] struct ResponseData { user: Option, } fn main() -> Result<(), Box> { // Successful response let success_json = r#"{ "data": { "user": { "id": 42, "name": "Alice" } }, "errors": null }"#; let response: Response = serde_json::from_str(success_json)?; assert_eq!(response.data.unwrap().user.unwrap().name, "Alice"); // Error response with detailed error information let error_json = r#"{ "data": null, "errors": [{ "message": "User not found", "locations": [{ "line": 2, "column": 3 }], "path": ["user"], "extensions": { "code": "NOT_FOUND" } }] }"#; let response: Response = serde_json::from_str(error_json)?; let error = &response.errors.unwrap()[0]; assert_eq!(error.message, "User not found"); assert_eq!(error.locations.as_ref().unwrap()[0], Location { line: 2, column: 3 }); assert_eq!(error.path.as_ref().unwrap()[0], PathFragment::Key("user".into())); // Display trait formats errors nicely println!("{}", error); // Output: user:2:3: User not found Ok(()) } ``` -------------------------------- ### Handle GraphQL Interface Types in Rust Source: https://context7.com/graphql-rust/graphql-client/llms.txt GraphQL interfaces are represented by a base struct containing common fields and an enum for type-specific fields. This allows accessing shared fields directly and using a match statement for type-specific data. Ensure the `response_derives` includes `PartialEq` if needed for comparisons. ```rust use graphql_client::GraphQLQuery; use serde_json::json; // schema.graphql: // interface Named { name: String! } // type Person implements Named { name: String!, birthday: String } // type Dog implements Named { name: String!, isGoodDog: Boolean! } #[derive(GraphQLQuery)] #[graphql( schema_path = "schema.graphql", query_path = "query.graphql", response_derives = "Debug, PartialEq" )] pub struct InterfaceQuery; fn main() { let response = json!({ "everything": [ { "__typename": "Person", "name": "Alice", "birthday": "1990-05-15" }, { "__typename": "Dog", "name": "Buddy", "isGoodDog": true } ] }); let data: interface_query::ResponseData = serde_json::from_value(response).unwrap(); for entity in data.everything.unwrap() { // Common interface field available on all variants println!("Name: {}", entity.name); // Type-specific fields via enum match entity.on { interface_query::InterfaceQueryEverythingOn::Person(p) => { println!(" Birthday: {:?}", p.birthday); } interface_query::InterfaceQueryEverythingOn::Dog(d) => { println!(" Good dog: {}", d.is_good_dog); } } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.