Rust quick start

Use the Fauna Core HTTP API to query e-commerce demo data using Rust’s reqwest HTTP client library.

 

  1. Create a database with demo data

    Log in to the Fauna Dashboard, and create a database with the following configuration:

    • Region group: Choose your preferred region group, which determines where your data resides.

    • Use demo data: Enabled.

    • Enable backups: Disabled.

    Leave the other options as is.

    Create demo database

  2. Create an authentication secret

    Fauna supports several types of authentication secrets. Create a key, which is a type of secret, with the built-in server-readonly role:

    1. In the Dashboard’s Explorer page, select your demo database.

    2. In the database’s Keys tab, click Create Key.

    3. Choose a Role of server (read-only).

    4. Click Save.

    5. Copy the Key Secret.

    Create a key

  3. Set the FAUNA_SECRET environment variable

    Set the FAUNA_SECRET environment variable to your key’s secret.

    export FAUNA_SECRET=<KEY_SECRET>
  4. Set up a Rust project

    Create and navigate to a new directory for your app. Then initialize a Rust project:

    mkdir app
    cd app
    cargo init

    In the app directory, add the following dependencies to Cargo.toml:

    # Cargo.tml
    ...
    
    [dependencies]
    # HTTP client
    reqwest = { version = "0.11", features = ["json"] }
    # Lets you run async tasks
    tokio = { version = "1", features = ["full"] }
    #  Serializer/deserializer for JSON
    serde = { version = "1.0", features = ["derive"] }
    serde_json = "1.0"
  5. Create a basic app

    In the app directory, replace the content of src/main.rs with the following code:

    use reqwest::{Client, header};
    use std::env;
    use serde_json::json;
    
    #[tokio::main]
    async fn main() {
        let fauna_secret = env::var("FAUNA_SECRET")
            .expect("FAUNA_SECRET environment variable is not set");
    
        // Define the Query API endpoint.
        let url = "https://db.fauna.com/query/1";
        let client = Client::new();
    
        // Define the headers.
        let mut headers = header::HeaderMap::new();
        headers.insert("Authorization", format!("Bearer {}", fauna_secret).parse().unwrap());
        headers.insert("Content-Type", "application/json".parse().unwrap());
        headers.insert("X-Format", "simple".parse().unwrap());
    
        // Define the FQL query.
        let query_payload = json!({
            "query": "Product.sortedByPriceLowToHigh() { name, description, price }"
        });
    
        // Make the HTTP request.
        let response = client.post(url)
            .headers(headers)
            .json(&query_payload)
            .send()
            .await
            .expect("Failed to send the request");
    
        // Output the response.
        match response.json::<serde_json::Value>().await {
            Ok(json) => println!("{}", serde_json::to_string_pretty(&json).unwrap()),
            Err(err) => eprintln!("Failed to parse response: {}", err),
        }
    }
  6. Create a basic app

    Run the app from the app directory.

    cargo run

    The app prints the Query API’s response. The data property contains the results of the query:

    {
      "data": {
        "data": [
          {
            "description": "Conventional, 1 ct",
            "name": "single lime",
            "price": 35
          },
          {
            "description": "Organic, 1 bunch",
            "name": "cilantro",
            "price": 149
          },
          {
            "description": "Conventional, 16 oz bag",
            "name": "limes",
            "price": 299
          },
          {
            "description": "Organic, 16 oz bag",
            "name": "organic limes",
            "price": 349
          },
          {
            "description": "Conventional Hass, 4ct bag",
            "name": "avocados",
            "price": 399
          },
          {
            "description": "Frozen Cheese",
            "name": "pizza",
            "price": 499
          },
          {
            "description": "Translucent 9 Oz, 100 ct",
            "name": "cups",
            "price": 698
          },
          {
            "description": "Giant Taco Pinata",
            "name": "taco pinata",
            "price": 2399
          },
          {
            "description": "Original Classic Donkey Pinata",
            "name": "donkey pinata",
            "price": 2499
          }
        ]
      },
      ...
    }
\