Client driver quick start

This quick start guides you through driver installation setup and shows how to programmatically submit an FQL query.

See Supported drivers for a list of supported drivers.

Create a database

  1. Sign up for a free account at https://dashboard.fauna.com/register and log in to your account.

  2. Click CREATE DATABASE to create a database.

  3. Give your database a Name.

  4. Choose your preferred Region Group.

  5. If you enable Backups, select the Backup Retention interval.

  6. Click the CREATE button.

    Your new database is listed on the Home page.

Get a database access token

You need an access token for your application code to access this database.

  1. In the Databases list, select your newly created database. This takes you to the Explorer page with your database highlighted.

  2. Hover over the database name to reveal the Keys icon. Click the key icon.

  3. In the Keys dialog, click CREATE KEY.

  4. The Database name is already populated. Choose Admin or Server Role and enter an optional Key Name.

  5. Click the SAVE button.

  6. Copy the KEY’S SECRET. This is the database access token that you must make available to your application.

Make sure you copy and save the secret and associate it with this database. This is the only time the secret is displayed.

Build and run an application

Fauna provides drivers for the supported programming languages, which make it easy to query your database. These steps are a simple, working setup and application that show you the basic programming requirements. To adapt an application to your programming environment, see the Supported drivers repositories for detailed setup options and driver capabilities.

Choose your programming language:

C#GoJavaScriptPython

 

  1. The drivers recognize the Fauna environment variables. Set the FAUNA_SECRET environment variable to your previously saved secret:

    export FAUNA_SECRET=<savedSecret>
  2. Install the Fauna driver:

    mkdir app
    cd app
    go mod init app
    go get github.com/fauna/fauna-go
    npm install fauna
    pip install fauna

    Navigate to your .Net or C# project directory and add the Fauna package to your project:

    dotnet add package Fauna --prerelease
    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
      </PropertyGroup>
    
      <ItemGroup>
        <PackageReference Include="Fauna" Version="0.1.0-beta" />
      </ItemGroup>
    
    </Project>
  3. This application creates a collection named myCollection and adds a People document to the collection.

    Learn more about the Collection Collection.create() and create() methods.

    Create an app.go file and add the following code:

    Create an app.mjs file and add the following code:

    Create an app.py file and add the following code:

    Create a Program.cs file and add the following code:

    namespace HelloFauna;
    using Fauna;
    using static Fauna.Query;
    
    class Program
    {
    	static async Task Main(string[] args)
    	{
    		var secret = Environment.GetEnvironmentVariable("FAUNA_SECRET");
    		if (string.IsNullOrEmpty(secret))
    		{
    			Console.WriteLine("Fauna secret is not valid");
    			return;
    		}
    		var cfg = new Configuration(secret);
    		var client = new Client(cfg);
    		var createCollection = FQL($@"
    			Collection.create({{ ""name"": ""myCollection"" }})
    		");
    	
    		var addToCollection = FQL($@"
    			myCollection.create({{
    				""name"": ""Jon Doe""
    			}})
    		");
    
    		try {
    			var result = await client.QueryAsync(createCollection);
    			Console.WriteLine($"Collection created: {result.Data}");
    			var addDocument = await client.QueryAsync(addToCollection);
    			Console.WriteLine($"Document added: {addDocument.Data}");
    		} catch (Exception e) {
    			Console.WriteLine($"Error creating collection: {e.Message}");
    		}
    	}
    }
    package main
    
    import (
        "fmt"
        "github.com/fauna/fauna-go"
    )
    
    func main() {
        client, clientErr := fauna.NewDefaultClient()
        if clientErr != nil {
            panic(clientErr)
        }
    
        createColl, _ := fauna.FQL(`Collection.create({ name: "myCollection" })`, nil)
        if _, err := client.Query(createColl); err != nil {
            panic(err)
        }
    
        createPeople, _ := fauna.FQL(`myCollection.create({ name: ${name}})`, map[string]any{"name": "People"})
        res, err := client.Query(createPeople)
        if err != nil {
            panic(err)
        }
    
        fmt.Println(res.Data.(*fauna.Document).Data["name"])
    }
    import { Client, fql } from "fauna";
    //const fauna = require("fauna");
    
    // configure your client
    const client = new Client();
    
    try {
      // build queries using the fql function
      const collection_query = fql`Collection.create({ name: "myCollection" })`;
      // execute the query
      const collection_result = await client.query(collection_query);
    
      // define some data in your app
      const people = { name: "People" };
    
      // query using your app's local variables
      const document_query = fql`
        myCollection.create(${people}) {
          id,
          ts,
          name
        }
      `;
      const document_result = await client.query(document_query);
      console.log(document_result);
    } catch (error) {
      console.log(error)
    }
    # Import the driver, and other required packages
    from fauna import fql
    from fauna.client import Client
    from fauna.errors import FaunaException
    
    # Instantiate a client
    client = Client()
    
    # Create a collection called 'myCollection'
    try:
        # create a collection
        create_col = fql('Collection.create({ name: "myCollection" })')
        result = client.query(create_col)
        # Show the result
        print(result)
    except FaunaException as e:
        # handle errors
        print(e)
  4. Run the application:

    go install .
    app
    node app.mjs
    python app.py

    When you run the example, you should see the following response:

    dotnet run
    Collection created: Fauna.Types.NamedDocument
    map[name:People]
    {
      data: {
        id: '361023370020520517',
        ts: TimeStub { isoString: '2023-04-03T21:32:45.610Z' },
        name: 'People'
      },
      summary: '',
      txn_ts: 1680557565610000,
      stats: {
        compute_ops: 1,
        read_ops: 1,
        write_ops: 1,
        query_time_ms: 75,
        contention_retries: 1,
        storage_bytes_read: 22,
        storage_bytes_write: 204
      }
    }
    QuerySuccess(query_tags={},static_type=None,stats=QueryStats(stats={'compute_ops': 1, 'read_ops': 1, 'write_ops': 1, 'query_time_ms': 193, 'storage_bytes_read': 664, 'storage_bytes_write': 380, 'contention_retries': 0}),summary='',traceparent='00-d9575336f25822a9bbdb350b151eb408-b2a589f10cab38df-00',txn_ts=1682964369620000,data=NamedDocument(name='myCollection',coll=Module(name='Collection'),ts=datetime.datetime(2023, 5, 1, 18, 6, 9, 620000, tzinfo=datetime.timezone.utc),data={'indexes':{},'constraints':[]}))

    If myCollection already exists, Fauna returns a descriptive message that illuminates the cause of the error. You can create another database or change the name of the myCollection collection in this example application and try again.

    If an authentication error occurs, try creating another key and go through the quick start again.

Fauna C# driver is LINQ (Language Integrated Query) compatible. Fauna.Mapping.Attributes and the Fauna.DataContext class provide the ability to bring your Fauna database schema into your code.

You can use attributes to map a POCO class to a Fauna document or object shape:

using Fauna.Mapping.Attributes;

[Object]
class Person
{
    // Property names are automatically converted to camelCase.
    [Field]
    public string? Id { get; set; }

    // Manually specify a name by providing a string.
    [Field("first_name")]
    public string? FirstName { get; set; }

    [Field("last_name")]
    public string? LastName { get; set; }

    [Field]
    public int Age { get; set; }
}

Your POCO classes can be used to drive deserialization:

var peopleQuery = FQL($@"Person.all()");
var people = client.PaginateAsync<Person>(peopleQuery).FlattenAsync();

await foreach (var p in people)
{
    Console.WriteLine($"{p.FirstName} {p.LastName}");
}

Write to your database:

var person = new Person { FirstName = "John", LastName = "Smith", Age = 42 };

var result = await client.QueryAsync($@"Person.create({person}).id");
Console.WriteLine(result.Data); // 69219723210223...

DataContext subclass provides a LINQ-compatible API for type-safe querying

// general query
db.Person.Where(p => p.FirstName == "John")
	.Select(p => new { p.FirstName, p.LastName })
	.First();

// or start with an index
db.Person.ByFirstName("John")
	.Select(p => new { p.FirstName, p.LastName })
	.First();

// There are async variants of methods which execute queries:

var syncCount = db.Person.Count();
var asyncCount = await db.Person.CountAsync();

Follow the C# driver repository for more information and query examples.

Next steps

Drivers

Become more familiar with the details of working with the supported Fauna drivers by reading the README file in the driver GitHub repository and installing and using the driver.

FQL language and API

Work through a graduated set of tutorials to get hands-on experience using Fauna and making FQL queries.

Fauna application examples

Discover more in-depth tutorials, code examples, and videos that show you how to use FQL in real applications.

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!