Ruby quick start

Use the Fauna Core HTTP API to query e-commerce demo data using Ruby’s Net::HTTP client library.

 

  1. Create a database with demo data

  2. Create an authentication secret

  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 an app

    Create and navigate to a new directory for your app;

    mkdir app
    cd app
  5. Create a basic app

    In the app directory, create an app.rb file and add the following code:

    require 'net/http'
    require 'uri'
    require 'json'
    
    # Define the Query API endpoint and headers.
    uri = URI("https://db.fauna.com/query/1")
    headers = {
      "Authorization" => "Bearer #{ENV['FAUNA_SECRET']}",
      "Content-Type" => "application/json",
      "X-Format" => "simple"
    }
    
    # Define the FQL query.
    query_payload = {
      query: "Product.sortedByPriceLowToHigh() { name, description, price }"
    }
    
    # Make the HTTP request.
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    request = Net::HTTP::Post.new(uri.path, headers)
    request.body = query_payload.to_json
    
    response = http.request(request)
    
    # Output the response.
    puts JSON.pretty_generate(JSON.parse(response.body))
  6. Run the app

    Run the app from the app directory.

    ruby app.rb

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

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