HTTP API user guide

The Fauna HTTP API user guide gives you instructions on how to submit Fauna Query Language (FQL) queries over HTTP to interact with your database.

HTTP API

Submitting queries and handling responses involves the following steps:

  1. Authenticate

  2. Submit request

  3. Handle response, including error responses

These steps are followed by a description of request and response value encoding.

Authenticate

API requests require authentication, so you must have an access token for your application code to access the database. By default, Fauna looks for a bearer token in the Authorization header.

Get an access token, also called a key secret, to use as the bearer token:

  1. In the Databases list on the Home page, select your 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. Choose a Role of admin or server and enter an optional Key Name.

  5. Click Save.

  6. Copy the Secret Key. This is the database access token to include in the Authorization: Bearer <accessToken> field of the request header.

    Example:

    -H 'Authorization: Bearer fnAFG_ebIVAARNZYT2Z1nMonmzHlw6wWxI6mLpTa'

    Make sure you copy and save the secret. This is the only time it is displayed.

    Optionally, set the $FAUNA_SECRET environment variable to the access token value.

Submit request

This example gets the set of collections given the endpoint URI, the header parameters, including the access token, and the FQL query as data, which is in the same format as Dashboard requests.

curl -X POST \
  'https://db.fauna.com/query/1' \
  -H 'Authorization: Bearer $FAUNA_SECRET' \
  -H 'Content-Type: application/json' \
  -d '{"query": "Collection.all()"}'

See Handle response for a description of the response to this example.

Header

Headers are used to control request behavior.

Override default or configured client settings. The headers you specify on the call to the client query function are applied, and anything you pass to the query function takes precedence over default headers regardless of how you pass them.

Fauna supports the following request header parameters:

Name Type Description

x-format

string

Defines the encoded format expected for the query arguments field and the data field of a successful response.

Options: simple, tagged

x-last-txn-ts

integer

If set, acts as the minimum snapshot time the query executes. Clients populate this based on the highest txn_ts result value observed of any transaction the client has processed.

x-linearized

boolean

If true, unconditionally run the query as strictly serialized. This affects read-only transactions because transactions that write are already strictly serialized. See Transactions.

x-max-contention-retries

integer

Maximum number of times the system retries a transaction because of contention failure before an error is returned.

x-query-tags

string

String-encoded set of caller-defined tags, which identify the request. Provided back in the logging and the query response body. The format is a list of key:value pairs. For example:

- foo=bar - foo=bar,baz=blah

Each key and each value may only include the characters [a-zA-Z0-9_]. These are also valid tags.

- foo_bar=baz - foo3=1234,5=6

All these are invalid.

- foo bar=3 // no spaces - foo=bar, // no trailing commas - foo==bar // too many =

Each key must be less than or equal to 40 bytes. Each value must be less than or equal to 80 bytes. There can be only a maximum of 25 key:value pairs, and the full header can’t exceed 3000 bytes.

x-query-timeout-ms

integer

Query timeout in milliseconds.

x-typecheck

boolean

Enable or disable type checking of the query before evaluation. Defaults to the value of typechecked on the database configuration.

Request body

The request body includes a query field and an optional arguments field:

{
  "query": "Author.all().where(.name == name)",
  "arguments": {
    "name": "Alice"
  }
}

 

The query field value is an FQL string that conforms to the FQL language reference specification. The arguments field is used to pass parameters to the query. The preceding example declares name as a parameter, so the query returns all Author documents that have a name value of Alice.

Handle response

A successful response to the Submit request example might be similar to the following:

{
  "data": {
    "data": [
      {
        "name": "testCollection00",
        "coll": "Collection",
        "ts": "2023-06-22T22:41:22.285Z",
        "indexes": {},
        "constraints": [],
        "history_days": 0
      }
    ]
  },
  "summary": "",
  "txn_ts": 1689511270210310,
  "stats": {
    "compute_ops": 1,
    "read_ops": 10,
    "write_ops": 0,
    "query_time_ms": 3,
    "contention_retries": 0,
    "storage_bytes_read": 568,
    "storage_bytes_write": 0,
    "rate_limits_hit": []
  },
  "schema_version": 0
}

 

The response to the Collections.all() query shows that the database has a single testCollection00 collection, returning the collection definition document and query performance metrics.

Response body

See the different response bodies returned for:

Successful query

Field Description

data

Query execution data result.

summary

txn_ts

Request timestamp. See the x-last-txn-ts header parameter.

stats

Query statistics:

Statistic Type Description

compute_ops

Int

Number of compute operations consumed by this query.

read_ops

Int

Number of read operations consumed by this query.

write_ops

Int

Number of write operations consumed by this query.

query_time_ms

Int

Query processing time, in milliseconds.

contention_retries

Int

Write contention retry count.

storage_bytes_read

Int

Amount of data read from storage, in bytes.

storage_bytes_write

Int

Amount of data written to storage, in bytes.

rate_limits_hit

An array of ops types that were limited or approaching rate limits:

  • read

  • write

  • compute

Example: [ "read", "compute" ]

schema_version

FSL version

Failed query

A query can fail because of one of these classes of errors:

Error classification Error cause

Check error

Before execution, one or more query validation checks failed.

Runtime error

An error occurred during query execution. This might include multiple errors and isn’t associated with a particular method.

Abort error

An abort() call caused the transaction to abort.

Example:

You can see that the response fields are the same as a successful response, except there is an error field describing the error instead of a data field, and the summary field includes more descriptive error information. This error is caused by misspelling the all() method.

{
    "error": {
        "code": "invalid_function_invocation",
        "message": "The function `al` doesn't exist on `Collection`"
    },
    "summary": "error: The function `al` doesn't exist on `Collection`\nat *query*:1:12\n  |\n1 | Collection.al()\n  |            ^^\n  |",
    "txn_ts": 1689785459623670,
    "stats": {
        "compute_ops": 1,
        "read_ops": 0,
        "write_ops": 0,
        "query_time_ms": 0,
        "contention_retries": 0,
        "storage_bytes_read": 0,
        "storage_bytes_write": 0,
        "rate_limits_hit": []
    },
    "schema_version": 0
}
Field Description

error

Field Description

code

message

Formatted message with detailed information about the cause of the error.

summary

txn_ts

Request timestamp. See the x-last-txn-ts header parameter.

stats

Query statistics:

Statistic Type Description

compute_ops

Int

Number of compute operations consumed by this query.

read_ops

Int

Number of read operations consumed by this query.

write_ops

Int

Number of write operations consumed by this query.

query_time_ms

Int

Query processing time, in milliseconds.

contention_retries

Int

Write contention retry count.

storage_bytes_read

Int

Amount of data read from storage, in bytes.

storage_bytes_write

Int

Amount of data written to storage, in bytes.

rate_limits_hit

An array of ops types that were limited or approaching rate limits:

  • read

  • write

  • compute

Example: [ "read", "compute" ]

schema_version

FSL version

Query status

The HTTP status code indicates the request completion status. You should try to first handle the error based on the Fauna error code. If the query returns an error code that isn’t included in the list, handle the error as appropriate for the HTTP status code.

The API HTTP API reference shows the status codes returned by each method.

HTTP status codes are grouped as follows:

Range Description

200-299

Successful query

HTTP status code Description

200

Successful operation.

400-499

Client error

HTTP status code Description

400

Failed operation, bad request.

401

Fauna can’t authenticate the request because of an invalid or missing authentication token.

409

Excessive contention on a document while executing a query.

429

Query exceeded a capacity limit.

440

Client timeout exceeded, but the timeout is set lower than the expected query processing time. Distinguished from a 503 status because this is considered a successful response regarding service availability.

500-599

Server error

HTTP status code Description

500

Unexpected error.

502

Router couldn’t reach the backend.

503

Unexpected timeout.

504

Router timeout trying to connect to the backend.

General status code reference: RFC9110 9110 HTTP Semantics

Value encoding

The Fauna HTTP API wire protocol data Types representation offers the following benefits:

  • Simplicity The format is easy to read with Fauna as a JSON-only endpoint, which facilitates developing and using drivers.

  • Consistency Ensures complex type information isn’t lost when converting Fauna values to JSON.

These objectives give you a query argument representation format that can be parsed by Fauna, and a response body that can be parsed by clients.

There are two encoding format options:

  • The tagged format includes typing information about every value.

    The tagged format can be parsed as input to Fauna. For example, you can write { "@date": "2022-12-08" } in JSON using the tagged format, and it is interpreted as a Date.

  • The simple format includes FQL literals that can be viewed in the dashboard and shell. It is a response-only format and can’t be used for query arguments.

Select the value encoding format

You can set the value encoding format in the request header.

Select the format by setting the x-format query header parameter:

Header Description

x-format

Request and response format options:

Value Description

tagged

Request and response are in Tagged format.

(default) simple

Response is in Simple format.

Tagged format

Example:

{
  "@doc": {
    "id": "368117669817221154",
    "coll": {
      "@mod": "Books"
    },
    "ts": {
      "@time": "2023-06-21T04:53:37.160Z"
    },
    "name": "Then and Now",
    "author": "W. Somerset Maugham",
    "data": {
      "data": "007571098 "
    }
  }
}

The tagged format has self-describing types. It is intended for drivers that can parse special types, such as Date and Time.

The tagged format is stable, machine-readable, and round-tripable, so you can send response data in the query parameters without making changes.

Parsing

For the tagged format to be used as an input, the Fauna types must be parsed from JSON. The following rules apply to parsing special types:

  • An object that includes a field starting with @ is parsed using the tagged value parser.

  • The object needs exactly matching fields to match a given type. If the object includes extra or missing fields, an error is reported with suggested fixes.

  • If the object has exactly matching fields, the values are parsed and result in an error if strings are incorrectly formatted.

The @object notation can be used when you want to declare an object with fields that include an @ symbol.

These rules also apply to drivers parsing this format.

Disambiguation

To send data that includes @, use the tagged @object value. For example:

{
  "not_a_date": {
    "@object": {
      "@date": "This is parsed as a string",
      "some other": "fields"
    }
  }
}

The following example doesn’t have the same effect because the @object tag affects only the first child:

{
  "@object": {
    "not_a_date": {
      "@date": "This is parsed as a date",
      "some other": "fields"
    }
  }
}

This example fails because the object with the @date key has a "some other": "fields" extra value, which isn’t allowed, and the @date value is an invalid date.

Simple format

Example:

{
  "id": "368117669817221154",
  "coll": "Books",
  "ts": "2023-06-21T04:53:37.160Z",
  "name": "Then and Now",
  "author": "W. Somerset Maugham",
  "data": {
    "data": "007571098 "
  }
}

With simple format, you can’t tell what the data types are from looking at the strings. This format is useful when you have a client without a driver. Typically, clients know the type of their data, so in this example, it is easy to select and parse the today and now fields.

Schema allows you to cast values in query arguments to their types. For example, if you have a Date in the collection schema, you can pass a string to Fauna, which is parsed as a Date when it is stored.

Format comparison

Type Tagged Simple

(See Number type)

JSON number

JSON string

JSON string

JSON array

JSON array

JSON object

JSON object

Object with keys prefixed with @

{ "@object": { …​ } }

JSON object

{ "@function": "now()" }

"[function now()]"

{ "@mod": "Date" }

Date

{ "@date": "2022-12-07" }

2022-12-07

{ "@time": "2022-12-07T16:30:00+0000" }

"2022-12-07T16:30:00+0000"

Set

{ "before": { "set": "ABCDE" }, "data": […​],}

{ "before": "ABCDE", "data": […​],}

{ "@bytes": "<Base64-encoded string>" }

<Base64-encoded string>

Number type

Long and Double types have a tagged format. The Int type is a JSON integer.

When using the Tagged format, this ensures that data read off the wire has the correct type, independent of the language.

Type Tagged format Simple format

Int (32-bit)

JSON number

JSON number

Long (64-bit)

{ "@long": "<number>" }

JSON number

Double (64-bit float)

{ "@double": "<number>" }

JSON number

Refs

Refs have a type that can be used to reference a document when no data is read. These are represented with the @ref tag:

{
  "@ref": {
    "id": "1234",
    "coll": {
      "@mod": "Foo"
    },

  }
}

You can reference a collection using the <coll>:<id> syntax. For example, to reference a collection named User, use Collection:User.

If you know the collection, you can paste and return the id value in another query and use the byId() method to get the document.

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!