• Start

Languages

Mojo

Connect to SurrealDB and run your first queries with the Mojo SDK.

The Mojo SDK for SurrealDB lets you connect to a database and query it from your application. This guide covers connecting, authenticating, and running your first queries.

Install the SDK, then import AsyncSurrealClient and ConnectOptions into your Mojo program.

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

Create a client and connect over HTTP, passing your namespace, database, and access token through ConnectOptions.

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 cm9vdDpyb290")),  # root:secret
        ),
    )

Supported connection protocols include:

  • HTTP

The access_token here is the base64 encoding of root:secret, sent as HTTP Basic auth.

The client exposes convenience methods that wrap common SurrealQL statements. Each takes the table or record to act on and a JSON document. Use create to insert a new record.

client.create("person", '{ "name": "Chiru", "age": 30 }')

Use select to retrieve a record or all records in a table.

client.select("person:chiru")

Use query to run any SurrealQL statement.

var resp = client.query("SELECT * FROM person WHERE age > 18;")

Every call returns an RpcResponse. Check is_ok() before reading the result, and inspect the error fields otherwise.

if resp.is_ok():
    if resp.result:
        print(resp.result.value())
else:
    print("code:", resp.error_code().value())
    print("message:", resp.error_message().value())

When you are finished, close the connection to release its resources.

client.close()

You have learned how to install the SDK, connect to SurrealDB, create records, and retrieve data. There is a lot more you can do with the SDK, including updating and deleting records, authentication, live queries, and transactions.

Note

This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the Mojo SDK reference.

Was this page helpful?