The SurrealDB Python SDK enables direct interaction with a SurrealDB instance, providing a powerful way to interact with the database.
First, install the SurrealDB SDK using pip:
pip install surrealdb
Alternatively, you can use install the SurrealDB SDK using poetry:
poetry add 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")
The Python SDK comes with a number of built-in functions.
Function | Description |
---|---|
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 SyntaxSurreal(url) SurrealHTTP(url)
NoteThe url is required in either the Surreal class or connect method
Arguments | Description | ||
---|---|---|---|
url required | 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')
.connect()
Connects to a local or remote database endpoint.
Method Syntaxdb.connect(url)
NoteThe url is required in either the Surreal class or connect method
Arguments | Description | ||
---|---|---|---|
url required | 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')
.close()
Closes the persistent connection to the database.
Method Syntaxdb.close()
db.close()
.use()
Switch to a specific namespace and database.
Method Syntaxdb.use(ns, db)
Arguments | Description | ||
---|---|---|---|
ns required | Switches to a specific namespace. | ||
db required | Switches to a specific database. |
await db.use('test', 'test')
.signup()
Signs up to a specific authentication scope.
Method Syntaxdb.signup(vars)
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', })
.signin()
Signs up to a specific authentication scope.
Method Syntaxdb.signin(vars)
Arguments | Description | ||
---|---|---|---|
vars required | Variables used in a signup query. |
token = await db.signin({ 'user': 'root', 'pass': 'root', })
.invalidate()
Invalidates the authentication for the current connection.
Method Syntaxdb.invalidate(vars)
await db.invalidate()
.authenticate()
Authenticates the current connection with a JWT token.
Method Syntaxdb.authenticate(token)
Arguments | Description | ||
---|---|---|---|
token required | The JWT authentication token. |
await db.authenticate('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJTdXJyZWFsREIiLCJpYXQiOjE1MTYyMzkwMjIsIm5iZiI6MTUxNjIzOTAyMiwiZXhwIjoxODM2NDM5MDIyLCJOUyI6InRlc3QiLCJEQiI6InRlc3QiLCJTQyI6InVzZXIiLCJJRCI6InVzZXI6dG9iaWUifQ.N22Gp9ze0rdR06McGj1G-h2vu6a6n9IVqUbMFJlOxxA')
.let()
Assigns a value as a parameter for this connection.
Method Syntaxdb.let(key, val)
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')
.query()
Runs a set of SurrealQL statements against the database.
Method Syntaxdb.query(sql, vars)
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']
.select()
Selects all records in a table, or a specific record, from the database.
Method Syntaxdb.select(thing)
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;
.create()
Creates a record in the database.
Method Syntaxdb.create(thing, data)
Arguments | Description | ||
---|---|---|---|
thing required | The table name or the specific record ID to create. | ||
data required | 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;
.update()
Updates all records in a table, or a specific record, in the database.
Method Syntaxdb.update(thing, data)
NoteThis 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;
.merge()
Modifies by deep merging all records in a table, or a specific record, in the database.
Method Syntaxdb.merge(thing, data)
NoteThis 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.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, }, })
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 Syntaxdb.patch(thing, data)
NoteThis 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.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" }, ])
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 Syntaxdb.delete(thing)
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;