Crates.io | reqwest-graphql |
lib.rs | reqwest-graphql |
version | 1.0.0 |
source | src |
created_at | 2022-01-21 20:33:24.826265 |
updated_at | 2022-01-21 20:33:24.826265 |
description | Minimal GraphQL client for Rust |
homepage | |
repository | |
max_upload_size | |
id | 518733 |
size | 14,407 |
Minimal GraphQL client for Rust. Forked from arthurkhlghatyan/gql-client-rs
use gql_client::Client;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
pub struct Data {
user: User
}
#[derive(Deserialize)]
pub struct User {
id: String,
name: String
}
#[derive(Serialize)]
pub struct Vars {
id: u32
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let endpoint = "https://graphqlzero.almansi.me/api";
let query = r#"
query UserByIdQuery($id: ID!) {
user(id: $id) {
id
name
}
}
"#;
let client = Client::new(endpoint);
let vars = Vars { id: 1 };
let data = client.query_with_vars::<Data, Vars>(query, vars).await.unwrap();
println!("Id: {}, Name: {}", data.user.id, data.user.name);
Ok(())
}
Client exposes new_with_headers function to pass headers using simple HashMap<&str, &str>
use gql_client::Client;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let endpoint = "https://graphqlzero.almansi.me/api";
let mut headers = HashMap::new();
headers.insert("authorization", "Bearer <some_token>");
let client = Client::new_with_headers(endpoint, headers);
Ok(())
}
There are two types of errors that can possibly occur. HTTP related errors (for example, authentication problem) or GraphQL query errors in JSON response. Debug, Display implementation of GraphQLError struct properly displays those error messages. Additionally, you can also look at JSON content for more detailed output by calling err.json()
use gql_client::Client;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
pub struct Data {
user: User
}
#[derive(Deserialize)]
pub struct User {
id: String,
name: String
}
#[derive(Serialize)]
pub struct Vars {
id: u32
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let endpoint = "https://graphqlzero.almansi.me/api";
// Send incorrect request
let query = r#"
query UserByIdQuery($id: ID!) {
user(id: $id) {
id1
name
}
}
"#;
let client = Client::new(endpoint);
let vars = Vars { id: 1 };
let error = client.query_with_vars::<Data, Vars>(query, vars).await.err();
println!("{:?}", error);
Ok(())
}