Skip to main content

Python SDK

The SurrealDB SDK for Python enables simple and advanced querying of a remote database from a browser or from server-side code. By default connections to SurrealDB are made over WebSockets, and automatically reconnect when the connection is terminated. We however also support connecting through a http client, however that is not as fully implemented yet.

To contribute to this documentation, edit this file on GitHub.

To contribute to the SDK code, submit an Issue or Pull Request here.

NOTE: This SDK is compatible with V1.x.x


Install the SDK

First, install the SurrealDB SDK using pip:

pip install surrealdb

Alternatively, you can use install the SurrealDB SDK using poetry:

poetry add surrealdb

Connect to SurrealDB

Create a new surreal.py file and add the following code to try out some basic operations using the SurrealDB SDK.

from surrealdb import Surreal

async def main():
"""Example of how to use the SurrealDB client."""
async with Surreal("ws://localhost:8000/rpc") as db:
await db.signin({"user": "root", "pass": "root"})
await db.use("test", "test")
await db.create(
"person",
{
"user": "me",
"pass": "safe",
"marketing": True,
"tags": ["python", "documentation"],
},
)
print(await db.select("person"))
print(await db.update("person", {
"user":"you",
"pass":"very_safe",
"marketing": False,
"tags": ["Awesome"]
}))
print(await db.delete("person"))

# You can also use the query method
# doing all of the above and more in SurrealQl

# In SurrealQL you can do a direct insert
# and the table will be created if it doesn't exist
await db.query("""
insert into person {
user: 'me',
pass: 'very_safe',
tags: ['python', 'documentation']
};

""")
print(await db.query("select * from person"))

print(await db.query("""
update person content {
user: 'you',
pass: 'more_safe',
tags: ['awesome']
};

"""))
print(await db.query("delete person"))

if __name__ == "__main__":
import asyncio

asyncio.run(main())

Then run your app from the command line with:

python surreal.py

Alternatively, you can run it in a notebook like Jupyter or VS code

# %%
"""Example of how to use the SurrealDB client in a notebook"""

from surrealdb import Surreal

db = Surreal("http://localhost:8000")
await db.connect()
await db.signin({"user": "root", "pass": "root"})
await db.use("test", "test")

# %%
await db.create(
"person",
{
"user": "me",
"pass": "safe",
"marketing": True,
"tags": ["python", "documentation"],
},
)

# %%
await db.select("person")

# %%
await db.update("person", {
"user":"you",
"pass":"very_safe",
"marketing": False,
"tags": ["Awesome"]
})

# %%
await db.delete("person")

SDK methods

The Python SDK comes with a number of built-in functions.

FunctionDescription
Surreal(url)Surreal is a class that represents a Surreal server.
db.connect()Connects to a local or remote database endpoint
db.close()Closes the persistent connection to the database
db.use(ns, db)Switch to a specific namespace and database
db.signup(vars)Signs this connection up to a specific authentication scope
db.signin(vars)Signs this connection in to a specific authentication scope
db.invalidate()Invalidates the authentication for the current connection
db.authenticate(token)Authenticates the current connection with a JWT token
db.let(key, val)Assigns a value as a parameter for this connection
db.query(sql, vars)Runs a set of SurrealQL statements against the database
db.select(thing)Selects all records in a table, or a specific record
db.create(thing, data)Creates a record in the database
db.update(thing, data)Updates all records in a table, or a specific record
db.merge(thing, data)Modifies by deep merging all records in a table, or a specific record, in the database
db.patch(thing, data)Applies JSON Patch changes to all records in a table, or a specific record
db.delete(thing)Deletes all records, or a specific record

Surreal()

Surreal is a class that represents a Surreal server. The default way to connect is through WebSockets using Surreal(url) If an http client is needed you can use SurrealHTTP(url) but be aware that it is currently not as stable and not as fully implemented.

Method Syntax
Surreal(url)
SurrealHTTP(url)

NOTE: The url is required in either the Surreal class or connect method

Arguments

ArgumentsDescription

url REQUIRED

The database endpoint to connect to.

Example usage

# Connect to a local endpoint
db = Surreal()
await db.connect('http://127.0.0.1:8000/rpc')
# Connect to a remote endpoint
db = Surreal()
await db.connect('https://cloud.surrealdb.com/rpc')

.connect()

Connects to a local or remote database endpoint.

Method Syntax
db.connect(url)

NOTE: The url is required in either the Surreal class or connect method

Arguments

ArgumentsDescription

url REQUIRED

The database endpoint to connect to.

Example usage

# Connect to a local endpoint
db = Surreal()
await db.connect('http://127.0.0.1:8000/rpc')
# Connect to a remote endpoint
db = Surreal()
await db.connect('https://cloud.surrealdb.com/rpc')

.close()

Closes the persistent connection to the database.

Method Syntax
db.close()

Example usage

db.close()

.use()

Switch to a specific namespace and database.

Method Syntax
db.use(ns, db)

Arguments

ArgumentsDescription
nsREQUIRED

Switches to a specific namespace.

dbREQUIRED

Switches to a specific database.

Example usage

await db.use('test', 'test')

.signup()

Signs up to a specific authentication scope.

Method Syntax
db.signup(vars)

Arguments

ArgumentsDescription
varsREQUIRED

Variables used in a signup query.

Example usage

token = await db.signup({
'NS': 'test',
'DB': 'test',
'SC': 'user',
'email': 'info@surrealdb.com',
'pass': '123456',
})

.signin()

Signs up to a specific authentication scope.

Method Syntax
db.signin(vars)

Arguments

ArgumentsDescription
varsREQUIRED

Variables used in a signup query.

Example usage

token = await db.signin({
'user': 'root',
'pass': 'root',
})

.invalidate()

Invalidates the authentication for the current connection.

Method Syntax
db.invalidate(vars)

Example usage

await db.invalidate()

.authenticate()

Authenticates the current connection with a JWT token.

Method Syntax
db.authenticate(token)

Arguments

ArgumentsDescription
tokenREQUIRED

The JWT authentication token.

Example usage

await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA')

.let()

Assigns a value as a parameter for this connection.

Method Syntax
db.let(key, val)

Arguments

ArgumentsDescription
keyREQUIRED

Specifies the name of the variable.

valREQUIRED

Assigns the value to the variable name.

Example usage

# Assign the variable on the connection
await db.let("name", {
"first": "Tobie",
"last": "Morgan Hitchcock",
})
# Use the variable in a subsequent query
await db.query('CREATE person SET name = $name')
# Use the variable in a subsequent query
await db.query('SELECT * FROM person WHERE name.first = $name.first')

.query()

Runs a set of SurrealQL statements against the database.

Method Syntax
db.query(sql, vars)

Arguments

ArgumentsDescription
sqlREQUIRED

Specifies the SurrealQL statements.

varsOPTIONAL

Assigns variables which can be used in the query.

Example usage

# Assign the variable on the connection
result = await db.query('CREATE person; SELECT * FROM type::table($tb)', {
'tb': 'person',
})
# Get the first result from the first query
result[0]['result'][0]
# Get all of the results from the second query
result[1]['result']

.select()

Selects all records in a table, or a specific record, from the database.

Method Syntax
db.select(thing)

Arguments

ArgumentsDescription
thingREQUIRED

The table name or a record ID to select.

Example usage

# Select all records from a table
people = await db.select('person')
# Select a specific record from a table
person = await db.select('person:h5wxrf2ewk8xjxosxtyc')

Translated query

This function will run the following query in the database:

SELECT * FROM $thing;

.create()

Creates a record in the database.

Method Syntax
db.create(thing, data)

Arguments

ArgumentsDescription
thingREQUIRED

The table name or the specific record ID to create.

dataREQUIRED

The document / record data to insert.

Example usage

# Create a record with a random ID
person = await db.create('person')
# Create a record with a specific ID
record = await db.create('person:tobie', {
'name': 'Tobie',
'settings': {
'active': true,
'marketing': true,
},
})

Translated query

This function will run the following query in the database:

CREATE $thing CONTENT $data;

.update()

Updates all records in a table, or a specific record, in the database.

Method Syntax
db.update(thing, data)

NOTE: This function replaces the current document / record data with the specified data.

Arguments

ArgumentsDescription
thingREQUIRED

The table name or the specific record ID to update.

dataOPTIONAL

The document / record data to insert.

Example usage

# Update all records in a table
people = await db.update('person')
# Update a record with a specific ID
person = await db.update('person:tobie', {
'name': 'Tobie',
'settings': {
'active': true,
'marketing': true,
},
})

Translated query

This function will run the following query in the database:

UPDATE $thing CONTENT $data;

.merge()

Modifies by deep merging all records in a table, or a specific record, in the database.

Method Syntax
db.merge(thing, data)

NOTE: This function merges the current document / record data with the specified data.

Arguments

ArgumentsDescription
thingREQUIRED

The table name or the specific record ID to change

dataOPTIONAL

The document / record data to insert.

Example usage

# Update all records in a table
people = await db.merge('person', {
updated_at: new Date(),
})
# Update a record with a specific ID
person = await db.merge('person:tobie', {
'updated_at': datetime.datetime.utcnow(),
'settings': {
'active': True,
},
})

Translated query

This function will run the following query in the database:

UPDATE $thing MERGE $data;

.patch()

Applies JSON Patch changes to all records, or a specific record, in the database.

Method Syntax
db.patch(thing, data)

NOTE: This function patches the current document / record data with the specified JSON Patch data.

Arguments

ArgumentsDescription
thingREQUIRED

The table name or the specific record ID to modify.

dataOPTIONAL

The JSON Patch data with which to modify the records.

Example usage

# Update all records in a table
people = await db.patch('person', [
{ 'op': "replace", 'path': "/created_at", 'value': str(datetime.datetime.utcnow()) },
])
# Update a record with a specific ID
person = await db.patch('person:tobie', [
{ 'op': "replace", 'path': "/settings/active", 'value': False },
{ 'op': "add", "path": "/tags", "value": ["developer", "engineer"] },
{ 'op': "remove", "path": "/temp" },
])

Translated query

This function will run the following query in the database:

UPDATE $thing PATCH $data;

.delete()

Deletes all records in a table, or a specific record, from the database.

Method Syntax
db.delete(thing)

Arguments

ArgumentsDescription
thingREQUIRED

The table name or a record ID to select.

Example usage

# Delete all records from a table
await db.delete('person')
# Delete a specific record from a table
await db.delete('person:h5wxrf2ewk8xjxosxtyc')

Translated query

This function will run the following query in the database:

DELETE * FROM $thing;