Skip to content

Using the CoCore API from Rust

To assist Rust developers in integrating with the CoCore GraphQL API, here's a comprehensive guide utilizing the graphql-client crate.

1. Add Dependencies

Begin by adding the necessary dependencies to your Cargo.toml file:

toml
[dependencies]
graphql-client = "0.14.0"
reqwest = { version = "0.11", features = ["blocking", "json"] }

2. Download the GraphQL Schema

To generate Rust types corresponding to your GraphQL queries, you'll need the GraphQL schema. You can obtain it using various tools, including the graphql-client CLI. Ensure the schema is saved as schema.graphql in your project directory.

3. Define GraphQL Queries

Create a .graphql file (e.g., src/queries/get_job.graphql) containing your GraphQL query:

graphql
query GetJob($id: ID!) {
  job(id: $id) {
    id
    name
    quantity
  }
}

4. Generate Rust Types

Use the graphql-client procedural macro to generate Rust types for your query. In your Rust code, define a module that references your schema and query:

rust
use graphql_client::GraphQLQuery;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "schema.graphql",
    query_path = "src/queries/get_job.graphql",
    response_derives = "Debug"
)]
struct GetJobQuery;

This will generate a module named get_job_query containing the necessary types.

5. Initialize the GraphQL Client

Set up the reqwest client with the appropriate headers, including your API key:

rust
use reqwest::blocking::Client;
use std::error::Error;

fn create_client(api_key: &str) -> Result<Client, Box<dyn Error>> {
    let client = Client::builder()
        .user_agent("graphql-rust/0.14.0")
        .default_headers(
            std::iter::once((
                reqwest::header::AUTHORIZATION,
                reqwest::header::HeaderValue::from_str(&format!("Bearer {}", api_key))?,
            ))
            .collect(),
        )
        .build()?;
    Ok(client)
}

6. Execute Queries and Handle Responses

Construct the variables for your query, send the request, and handle the response:

rust
use get_job_query::{Variables, ResponseData};
use graphql_client::reqwest::post_graphql_blocking as post_graphql;

fn fetch_job(client: &Client, job_id: &str) -> Result<(), Box<dyn Error>> {
    let variables = Variables { id: job_id.to_string() };
    let response = post_graphql::<GetJobQuery, _>(
        client,
        "$MY_COCORE_URL/graphql",
        variables,
    )?;

    if let Some(data) = response.data {
        if let Some(job) = data.job {
            println!("ID: {}, Name: {}, Quantity: {}", job.id, job.name, job.quantity);
        } else {
            println!("Job not found.");
        }
    } else if let Some(errors) = response.errors {
        for error in errors {
            println!("Error: {}", error.message);
        }
    }

    Ok(())
}

7. Putting It All Together

Here's how you can integrate the above components:

rust
fn main() -> Result<(), Box<dyn Error>> {
    let api_key = "YOUR_API_KEY";
    let client = create_client(api_key)?;
    let job_id = "job-id";

    fetch_job(&client, job_id)?;

    Ok(())
}

8. Explore API Documentation

For detailed information on available queries, mutations, and schema definitions, refer to the CoCore API documentation at https://docs.wearecococo.com.

By following these steps, Rust developers can effectively integrate with the CoCore GraphQL API using the graphql-client crate.

Connect. Combine. Collaborate.
The pioneering open integration platform, dedicated to transforming connectivity in the printing industry.