Client application quick start

Fauna supports drivers in several popular programming languages for programmatic management and manipulation of Fauna databases. To get started, complete the prerequisites and then select a language.

For a complete list of supported drivers, see Drivers.

Prerequisites

To use a Fauna driver, you must have:

  1. Sign up for a free account

  2. Create a database

    Click NEW DATABASE. Select the Classic region group.

  3. Create an access key

    Click SECURITY in the left-side navigation menu. Create a new key for your database. Be sure to save the key’s secret in a safe place, as it is only displayed once.

For a more detailed description of the signup and database creation steps, see the Dashboard quick start.

When you’re ready with a database and an access key, select a language to get started with a driver.

Choose a language

C#GoJavaJavaScriptPython

 

C#

For complete C# driver information, see the driver page.

Go

For complete Go driver information, see the driver page.

Java

For complete Java driver information, see the driver page.

JavaScript

For complete JavaScript driver information, see the driver page.

Python

For complete Python driver information, see the driver page.

Scala

For complete Scala driver information, see the driver page.

  1. Install the driver

    1. On Windows system, install Visual Studio. On macOS or Linux, install Mono.

    2. Install .Net Core 3.1.

    3. Open a terminal window and navigate to the folder where the project should live.

    4. Create the folder example, and the enter it.

    5. With your preferred text editor, create a new file called example.csproj. Add the following lines to the file:

      <Project Sdk="Microsoft.NET.Sdk">
          <PropertyGroup>
              <OutputType>Exe</OutputType>
              <TargetFramework>netcoreapp3.1</TargetFramework>
          </PropertyGroup>
          <ItemGroup>
              <PackageReference Include="FaunaDB.Client" Version="4.1.0" />
          </ItemGroup>
      </Project>

    Enter the following at the command line:

    go get github.com/fauna/faunadb-go/v4/faunadb
    1. Install Maven for your system.

    2. In a terminal window, navigate to the folder that should contain the Java project, then run the following command:

      mvn archetype:generate \
        -DgroupId=example \
        -DartifactId=example \
        -DarchetypeArtifactId=maven-archetype-quickstart \
        -DinteractiveMode=false
    3. Enter the example folder.

    4. Edit the pom.xml file so that it contains the following lines:

      <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>example</groupId>
        <artifactId>example</artifactId>
        <packaging>jar</packaging>
        <version>1.0-SNAPSHOT</version>
        <name>example</name>
        <url>http://maven.apache.org</url>
      
        <dependencies>
          <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
          </dependency>
          <dependency>
            <groupId>com.faunadb</groupId>
            <artifactId>faunadb-java</artifactId>
            <version>4.1.2</version>
            <scope>compile</scope>
          </dependency>
        </dependencies>
      
        <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          <maven.compiler.source>1.7</maven.compiler.source>
          <maven.compiler.target>1.7</maven.compiler.target>
        </properties>
      
        <build>
          <plugins>
            <plugin>
              <!-- Build an executable JAR -->
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-jar-plugin</artifactId>
              <version>3.1.0</version>
              <configuration>
                <archive>
                  <manifest>
                    <addC\lasspath>true</addClasspath>
                    <classpathPrefix>lib/</classpathPrefix>
                    <mainC\lass>example.App</mainClass>
                  </manifest>
                </archive>
              </configuration>
            </plugin>
          </plugins>
        </build>
      </project>

    Enter the following at the command line:

    npm install --save faunadb

    Enter the following at the command line:

    pip install faunadb
    1. Install sbt, for macOS, Windows, or Linux.

    2. In a terminal window, navigate to the folder that should contain the Scala project, then run the following command:

      sbt new scala/hello-world.g8
    3. When prompted for a name, enter example.

    4. Enter the example folder.

    5. Edit the build.sbt file so that it contains the following lines:

      import sbt._
      
      ThisBuild / scalaVersion := "2.12.8"
      ThisBuild / version := "0.1.0"
      ThisBuild / organization := "com.example"
      ThisBuild / organizationName := "example"
      
      lazy val root = (project in file("."))
        .settings(
          name := "example",
          libraryDependencies += "org.slf4j" % "slf4j-nop" % "1.7.28",
          libraryDependencies += "com.faunadb" %% "faunadb-scala" % "{driver-jvm-version}"
        )
      
      assemblyMergeStrategy in assembly := {
        case x if x.endsWith("io.netty.versions.properties") =>
          MergeStrategy.discard
        case "module-info.class" =>
          MergeStrategy.discard
        case x =>
          val oldStrategy = (assemblyMergeStrategy in assembly).value
          oldStrategy(x)
      }
    6. Edit the project/assembly.scala file so that it contains the following lines:

      addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.15.0")
  2. Create a program file

    With your preferred text editor, create a new file called Program.cs. We’ll use this file to run a Fauna query which creates a new collection named myCollection.

    Add the following lines to your file:

    With your preferred text editor, create a new file called app.go. We’ll use this file to run a Fauna query which creates a new collection named myCollection.

    Add the following lines to your file:

    With your preferred text editor, edit the src/main/java/example/fauna/App.java file. We’ll use this file to run a Fauna query which creates a new collection named myCollection.

    Modify the file to contain the following lines:

    With your preferred text editor, create a new file called app.js. We’ll use this file to run a Fauna query which creates a new collection named myCollection.

    Add the following lines to your file:

    With your preferred text editor, create a new file called app.py. We’ll use this file to run a Fauna query which creates a new collection called myCollection.

    Add the following lines to your file:

    With your preferred text editor, edit the src/main/scala/Main.scala file. We’ll use this file to run a Fauna query which creates a new collection named myCollection.

    Modify the file to contain the following lines:

    namespace Example
    {
        // Import the driver and other dependencies
        using System;
        using System.Threading.Tasks;
        using FaunaDB.Client;
        using FaunaDB.Collections;
        using FaunaDB.Query;
        using FaunaDB.Types;
        using Newtonsoft.Json;
    
        using static FaunaDB.Query.Language;
    
        public class Program
        {
            public static void Main(string[] args)
            {
                // Acquire the secret and optional endpoint from environment
                // variables.
                var secret = System.Environment.GetEnvironmentVariable("FAUNADB_SECRET");
                if (secret == null)
                {
                    Console.WriteLine("The FAUNADB_SECRET environment is not set... exiting.");
                    System.Environment.Exit(1);
                }
    
                var endpoint = System.Environment.GetEnvironmentVariable("FAUNADB_ENDPOINT");
                if (endpoint == null)
                {
                    endpoint = "https://db.fauna.com/";
                }
    
                Run(endpoint, secret).Wait();
                System.Environment.Exit(0);
            }
    
            public static async Task Run(string endpoint, string secret)
            {
                // Instantiate a client
                var client = new FaunaClient(
                    endpoint: endpoint,
                    secret: secret
                );
    
                try
                {
                    // Create a collection named 'myCollection'
                    Value result = await client.Query(
                        CreateCollection(Obj("name", "myCollection"))
                    );
    
                    // Show the result
                    Console.WriteLine(result);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"ERROR: {e.Message}");
                }
            }
        }
    }
    package main
    
    // Import the driver
    import (
    	"fmt"
    	f "github.com/fauna/faunadb-go/v4/faunadb"
    	"os"
    )
    
    // Acquire the secret and optional endpoint from environment variables
    var (
    	secret = os.Getenv("FAUNADB_SECRET")
    	endpoint = os.Getenv("FAUNADB_ENDPOINT")
    )
    
    func main() {
    	if secret == "" {
    		fmt.Println("The FAUNADB_SECRET environment variable is not set, exiting.")
    		os.Exit(1)
    	}
    
    	if endpoint == "" {
    		endpoint = "https://db.fauna.com/"
    	}
    
    	// Instantiate a client
    	client := f.NewFaunaClient(secret, f.Endpoint(endpoint))
    
    	// Create a collection called 'myCollection'
    	result, err := client.Query(
    		f.CreateCollection(f.Obj{"name": "myCollection"}))
    
    	// Show the output
    	if err != nil {
    		fmt.Fprintln(os.Stderr, err)
    	} else {
    		fmt.Println(result)
    	}
    }
    package example;
    
    // Import the driver
    import static com.faunadb.client.query.Language.*;
    import static com.faunadb.client.query.Language.TimeUnit.*;
    import static com.faunadb.client.types.Codec.*;
    import static com.faunadb.client.types.Value.NullV.NULL;
    
    import com.faunadb.client.FaunaClient;
    import com.faunadb.client.types.*;
    import com.faunadb.client.types.Value.*;
    
    /**
    * The class for our example app code.
    */
    public class App {
        /**
        * The example.
        */
        public static void main(String[] args) throws Exception {
            // Acquire the secret and optional endpoint from environment
            // variables
            String secret   = System.getenv("FAUNADB_SECRET");
            String endpoint = System.getenv("FAUNADB_ENDPOINT");
    
            if (secret == null || secret == "") {
                System.out.println(
                    "The FAUNADB_SECRET environment variable is not set, exiting."
                );
                System.exit(1);
            }
            if (endpoint == null || endpoint == "") {
                endpoint = "https://db.fauna.com/";
            }
    
            // Instantiate a client
            FaunaClient client = FaunaClient.builder()
                .withSecret(secret)
                .withEndpoint(endpoint)
                .build();
    
            System.out.println(
                client.query(
                    CreateCollection(Obj("name", Value("myCollection")))
                ).get()
            );
        }
    }
    // Require the driver
    const faunadb = require('faunadb')
    const q = faunadb.query
    
    // Acquire the secret and optional endpoint from environment variables
    const secret = process.env.FAUNADB_SECRET
    var endpoint = process.env.FAUNADB_ENDPOINT
    
    if (typeof secret === 'undefined' || secret === '') {
      console.error('The FAUNADB_SECRET environment variable is not set, exiting.')
      process.exit(1)
    }
    
    if (!endpoint) endpoint = 'https://db.fauna.com/'
    
    var mg, domain, port, scheme
    if ((mg = endpoint.match(/^(https?):\/\/([^:]+)(:(\d+))?/))) {
      scheme = mg[1] || 'https'
      domain = mg[2] || 'db.fauna.com'
      port = mg[4] || 443
    }
    
    // Instantiate a client
    const client = new faunadb.Client({
      secret: secret,
      domain: domain,
      port: port,
      scheme: scheme,
    })
    
    // Create a collection called 'myCollection'
    client.query(
      q.CreateCollection({ name: 'myCollection' })
    )
    
    // Show the result
    .then((ret) => console.log(ret))
    .catch((err) => console.error(
      'Error: [%s] %s: %s',
      err.name,
      err.message,
      err.errors()[0].description,
    ))
    # Import the driver, and other required packages
    import os
    import sys
    from urllib.parse import urlparse
    from faunadb import query as q
    from faunadb.client import FaunaClient
    
    # Acquire the secret and optional endpoint from environment variables
    secret = os.getenv("FAUNADB_SECRET")
    endpoint = os.getenv("FAUNADB_ENDPOINT")
    
    if not secret:
      print("The FAUNADB_SECRET environment variable is not set, exiting.")
      sys.exit(1)
    
    endpoint = endpoint or "https://db.fauna.com/"
    
    o = urlparse(endpoint)
    
    # Instantiate a client
    client = FaunaClient(
      secret=secret,
      domain=o.hostname,
      port=o.port,
      scheme=o.scheme
    )
    
    # Create a collection called 'myCollection'
    result = client.query(
      q.create_collection({"name": "myCollection"})
    )
    
    # Show the result
    print(result)
    The Shell version of this example is not currently available.
  3. Run the program

    Run the following command in a terminal window, in the directory where you created the program file. Be sure to replace YOUR_FAUNA_SECRET with the secret that you created at the beginning of this guide.

    Run the following command in a terminal window, in the directory where you created the project. Be sure to replace YOUR_FAUNA_SECRET with the secret that you created at the beginning of this guide.

    FAUNADB_SECRET=YOUR_FAUNA_SECRET dotnet run
    FAUNADB_SECRET=YOUR_FAUNA_SECRET go run app.go
    FAUNADB_SECRET=YOUR_FAUNA_SECRET mvn clean package \
      && java -jar target/example-1.0-SNAPSHOT.jar
    FAUNADB_SECRET=YOUR_FAUNA_SECRET node app.js
    FAUNADB_SECRET=YOUR_FAUNA_SECRET python app.py
    FAUNADB_SECRET=YOUR_FAUNA_SECRET sbt run

    You should see the result of your CreateCollection query:

    ObjectV(ref: RefV(id = "myCollection", collection = RefV(id = "collections")),ts: LongV(1633476829160000),history_days: LongV(30),name: StringV(myCollection))
    map[history_days:30 name:myCollection ref:{myCollection 0xc0000924b0 0xc0000924b0 <nil>} ts:1633458042080000]
    {ref: ref(id = "myCollection", collection = ref(id = "collections")), ts: 1633470945680000, history_days: 30, name: "myCollection"}
    {
      ref: Collection("myCollection"),
      ts: 1633458045000000,
      history_days: 30,
      name: 'myCollection'
    }
    {'ref': Ref(id=myCollection, collection=Ref(id=collections)), 'ts': 1633458048030000, 'history_days': 30, 'name': 'myCollection'}
    The Shell version of this example is not currently available.
  4. Learn more

    Fauna’s query model relies on indexes to support all query patterns which do not involve looking up documents directly by their Reference. An understanding of index creation and usage is crucial for effective Fauna development.

    See the Index tutorials for more information.

    To learn more about Fauna, Fauna Query Language, and the C# driver, explore the documentation:

    To learn more about Fauna, Fauna Query Language, and the Go driver, explore the documentation:

    To learn more about Fauna, Fauna Query Language, and the Java driver, explore the documentation:

    To learn more about Fauna, Fauna Query Language, and the JavaScript driver, explore the documentation:

    To learn more about Fauna, Fauna Query Language, and the Python driver, explore the documentation:

    To learn more about Fauna, Fauna Query Language, and the Scala driver, explore the documentation:

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!