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.
1. Install the SDK
Install the SDK, then import AsyncSurrealClient and ConnectOptions into your Mojo program.
from surrealdb import AsyncSurrealClient, ConnectOptions
from std.collections import Optional2. Connect to SurrealDB
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.
3. Inserting data into SurrealDB
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 }')4. Retrieving data from SurrealDB
Selecting records
Use select to retrieve a record or all records in a table.
client.select("person:chiru")Running SurrealQL queries
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())5. Closing the connection
When you are finished, close the connection to release its resources.
client.close()Next steps
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.
This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the Mojo SDK reference.