Skip to content

Concepts

Connecting to SurrealDB

The Mojo SDK connects to a SurrealDB instance with connect(), which takes an endpoint URL and an optional ConnectOptions. The URL scheme selects the transport. The endpoint path is /rpc.

MethodDescription
client.connect()Connects to a database endpoint
client.use()Switches to a specific namespace and database
client.close()Closes the connection
client.health()Runs a health check against the server
client.version()Returns the version of the connected server

Connects to a database endpoint. The URL scheme selects the transport (http, https, ws, or wss).

Method Syntax
client.connect(endpoint, connect_options)
ArgumentDescription
endpointThe database endpoint to connect to, ending in /rpc.
connect_optionsAn optional ConnectOptions carrying the namespace, database, credentials, TLS setting, and wire format.
from surrealdb import AsyncSurrealClient, ConnectOptions
from std.collections import Optional


def main():
    var client = AsyncSurrealClient()
    _ = client.connect(
        "http://localhost:8000/rpc",
        ConnectOptions(
            namespace=Optional(String("test")),
            database=Optional(String("test")),
            access_token=Optional(String("Basic cm9vdDpzZWNyZXQ=")),
        ),
    )

connect() returns a Bool.

The SDK ships transports for four schemes:

SchemeTransportNotes
http://HTTP/1.1Request and response querying. The most thoroughly tested path.
https://HTTP/1.1 over TLSBuild with -D HTTPS=1. See TLS.
ws://WebSocketStateful sessions, server-side transactions, and live queries.
wss://WebSocket over TLSBuild with -D HTTPS=1.
Note

WebSocket support is rolling out. For request and response querying, including atomic multi-statement transactions, use the HTTP or HTTPS transport.

ConnectOptions carries the namespace, database, credentials, and wire format for the connection.

Field

Description

namespace

The namespace to use. Sent as the

Surreal-NS

header.

database

The database to use. Sent as the

Surreal-DB

header.

access_token

The credential placed in the

Authorization

header. See Authentication.

tls_insecure

Disables TLS certificate verification. Dev fixtures only. Defaults to

False

.

formatRpcFormat.CBOR

(default) or

RpcFormat.JSON

.

The Surreal-NS and Surreal-DB headers are sent automatically when namespace and database are set.

Both protocols use the same /rpc endpoint and the same RPC methods. Pick the wire format with ConnectOptions.format:

from surrealdb import AsyncSurrealClient, ConnectOptions, RpcFormat
from std.collections import Optional


def main():
    var client = AsyncSurrealClient()
    _ = client.connect(
        "http://localhost:8000/rpc",
        ConnectOptions(
            namespace=Optional(String("test")),
            database=Optional(String("test")),
            access_token=Optional(String("Basic cm9vdDpzZWNyZXQ=")),
            format=RpcFormat.JSON,  # or RpcFormat.CBOR (default)
        ),
    )
    var resp = client.query("RETURN 1 + 1;")

Switching format swaps the Content-Type and Accept headers (application/json versus application/cbor) and the codec used to encode and decode the RPC envelope. Everything else stays the same.

CBOR is the default because it is what the SurrealDB server uses internally and the most compact on the wire. JSON is useful when you want to inspect traffic in DevTools, match the SurrealDB JavaScript SDK behaviour, or proxy through a JSON-only gateway.

Certificates are validated against the system root store by default. For self-signed dev fixtures, set tls_insecure=True:

ConnectOptions(
    namespace=Optional(String("test")),
    access_token=Optional(String("Basic cm9vdDpzZWNyZXQ=")),
    tls_insecure=True,  # never use in production
)

For the build flags required to connect over https:// or wss://, see Build with HTTPS.

Switches the connection to a specific namespace and database.

Method Syntax
client.use(namespace, database, session)
ArgumentDescription
namespaceThe namespace to switch to.
databaseThe database to switch to.
sessionAn optional session id to scope the change to a specific session.
client.use("test", "test")

Closes the connection and releases the active transport.

Method Syntax
client.close()

This method takes no arguments.

client.close()

Runs a health check to verify that the server is reachable and accepting commands.

Method Syntax
client.health()

This method takes no arguments.

client.health()

If the server is unreachable, the call raises a ConnectionError.

Returns the version of the connected SurrealDB server as an RpcResponse.

Method Syntax
client.version()

This method takes no arguments.

var resp = client.version()
if resp.is_ok() and resp.result:
    print(resp.result.value())

Two helpers report the state of the connection and the features the active transport supports:

if client.is_connected():
    var caps = client.capabilities()

capabilities() returns an EngineCapabilities describing which RPC features the active transport supports (live queries, sessions, server-side transactions, and the API endpoint). The client checks these flags before issuing a request, and raises an UnsupportedFeatureError rather than sending a request the server would reject.

Was this page helpful?

Last updated