Ruby quick start
Use the Fauna Core HTTP API to query e-commerce demo data using Ruby’s Net::HTTP client library.
-
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 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:-
In the Dashboard’s Explorer page, select your demo database.
-
In the database’s Keys tab, click Create Key.
-
Choose a Role of server (read-only).
-
Click Save.
-
Copy the Key Secret.
-
-
Set the FAUNA_SECRET environment variable
Set the
FAUNA_SECRET
environment variable to your key’s secret.export FAUNA_SECRET=<KEY_SECRET>
-
Set up an app
Create and navigate to a new directory for your app;
mkdir app cd app
-
Create a basic app
In the
app
directory, create anapp.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))
-
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 } ] }, ... }