Back to top
  Back

Python driver for SurrealDB

The SurrealDB library 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.

Install the library

First, install the SurrealDB library using pip:

pip install surrealdb

Alternatively, you can use install the SurrealDB library 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 driver.

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")

Library methods

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

Function Description
Surreal(url) static 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(url) / SurrealHTTP(url)

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.

The url is required in either the Surreal class or connect method
Arguments Description
The url of the database endpoint to connect to.
# 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')

db.connect(url)

Connects to a local or remote database endpoint.

The url is required in either the Surreal class or connect method
Arguments Description
The url of the database endpoint to connect to.
# 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')

db.close()

Closes the persistent connection to the database.

db.close()

db.use(ns, db)

Switch to a specific namespace and database.

Arguments Description
ns Required Switches to a specific namespace.
db Required Switches to a specific database.
await db.use('test', 'test')

db.signup(vars)

Signs up to a specific authentication scope.

Arguments Description
vars Required Variables used in a signup query.
token = await db.signup({
	'NS': 'test',
	'DB': 'test',
	'SC': 'user',
	'email': 'info@surrealdb.com',
	'pass': '123456',
})

db.signin(vars)

Signs in to a specific authentication scope.

Arguments Description
vars Required Variables used in a signin query.
token = await db.signin({
	'user': 'root',
	'pass': 'root',
})

db.invalidate()

Invalidates the authentication for the current connection.

await db.invalidate()

db.authenticate(token)

Authenticates the current connection with a JWT token.

Arguments Description
token Required The JWT authentication token.
await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA')

db.let(key, val)

Assigns a value as a parameter for this connection.

Arguments Description
key Required Specifies the name of the variable.
val Required Assigns the value to the variable name.
# 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')

db.query(sql, vars)

Runs a set of SurrealQL statements against the database.

Arguments Description
sql Required Specifies the SurrealQL statements.
vars Optional Assigns variables which can be used in the query.
# 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']

db.select(thing)

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

Arguments Description
thing Required The table name or a record ID to select.
# Select all records from a table
people = await db.select('person')
# Select a specific record from a table
person = await db.select('person:h5wxrf2ewk8xjxosxtyc')

This function will run the following query in the database:

SELECT * FROM $thing;

db.create(thing, data)

Creates a record in the database.

Arguments Description
thing Required The table name or the specific record ID to create.
data Optional The document / record data to insert.
# 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,
	},
})

This function will run the following query in the database:

CREATE $thing CONTENT $data;

db.update(thing, data)

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

This function replaces the current document / record data with the specified data.
Arguments Description
thing Required The table name or the specific record ID to update.
data Optional The document / record data to insert.
# 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,
	},
})

This function will run the following query in the database:

UPDATE $thing CONTENT $data;

db.merge(thing, data)

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

This function merges the current document / record data with the specified data.
Arguments Description
thing Required The table name or the specific record ID to change
data Optional The document / record data to insert.
# Update all records in a table
people = await db.change('person', {
	updated_at: new Date(),
})
# Update a record with a specific ID
         person = await db.change('person:tobie', {
             'updated_at': datetime.datetime.utcnow(),
             'settings': {
                 'active': True,
                 },
             })

This function will run the following query in the database:

UPDATE $thing MERGE $data;

db.patch(thing, data)

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

This function patches the current document / record data with the specified JSON Patch data.
Arguments Description
thing Required The table name or the specific record ID to modify.
data Optional The JSON Patch data with which to modify the records.
# Update all records in a table
people = await db.modify('person', [
	{ 'op': "replace", 'path': "/created_at", 'value': str(datetime.datetime.utcnow()) },
])
# Update a record with a specific ID
person = await db.modify('person:tobie', [
             { 'op': "replace", 'path': "/settings/active", 'value': False },
             { 'op': "add", "path": "/tags", "value": ["developer", "engineer"] },
             { 'op': "remove", "path": "/temp" },
])

This function will run the following query in the database:

UPDATE $thing PATCH $data;

db.delete(thing)

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

Arguments Description
thing Required The table name or a record ID to select.
# Delete all records from a table
await db.delete('person')
# Delete a specific record from a table
await db.delete('person:h5wxrf2ewk8xjxosxtyc')

This function will run the following query in the database:

DELETE * FROM $thing;