The official SurrealDB SDK for Python.
# Using pip
pip install surrealdb
# Using uv
uv add surrealdbIn this short guide, you will learn how to install, import, and initialize the SDK, as well as perform the basic data manipulation queries.
This guide uses the Surreal class, but this example would also work with AsyncSurreal class, with the addition of await in front of the class methods.
You can run SurrealDB locally or start with a free SurrealDB cloud account.
For local, two options:
- Install SurrealDB and run SurrealDB. Run in-memory with:
surreal start -u root -p rootdocker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start# Import the Surreal class
from surrealdb import Surreal
# Using a context manger to automatically connect and disconnect
with Surreal("ws://localhost:8000/rpc") as db:
db.signin({"username": 'root', "password": 'root'})
db.use("namepace_test", "database_test")
# Create a record in the person table
db.create(
"person",
{
"user": "me",
"password": "safe",
"marketing": True,
"tags": ["python", "documentation"],
},
)
# Read all the records in the table
print(db.select("person"))
# Update all records in the table
print(db.update("person", {
"user":"you",
"password":"very_safe",
"marketing": False,
"tags": ["Awesome"]
}))
# Delete all records in the table
print(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
# Create
db.query("""
insert into person {
user: 'me',
password: 'very_safe',
tags: ['python', 'documentation']
};
""")
# Read
print(db.query("select * from person"))
# Update
print(db.query("""
update person content {
user: 'you',
password: 'more_safe',
tags: ['awesome']
};
"""))
# Delete
print(db.query("delete person"))SurrealDB can also run embedded directly within your Python application natively. This provides a fully-featured database without needing a separate server process.
The embedded database is included when you install surrealdb.
For source builds, you'll need Rust toolchain and maturin:
uv run maturin develop --releasePerfect for embedded applications, development, testing, caching, or temporary data.
import asyncio
from surrealdb import AsyncSurreal
async def main():
# Create an in-memory database (can use "mem://" or "memory")
async with AsyncSurreal("memory") as db:
await db.use("test", "test")
await db.signin({"username": "root", "password": "root"})
# Use like any other SurrealDB connection
person = await db.create("person", {
"name": "John Doe",
"age": 30
})
print(person)
people = await db.select("person")
print(people)
asyncio.run(main())For persistent local storage:
import asyncio
from surrealdb import AsyncSurreal
async def main():
# Create a file-based database (can use "file://" or "surrealkv://")
async with AsyncSurreal("file://mydb") as db:
await db.use("test", "test")
await db.signin({"username": "root", "password": "root"})
# Data persists across connections
await db.create("company", {
"name": "Acme Corp",
"employees": 100
})
companies = await db.select("company")
print(companies)
asyncio.run(main())The embedded database also supports the blocking API:
from surrealdb import Surreal
# In-memory (can use "mem://" or "memory")
with Surreal("memory") as db:
db.use("test", "test")
db.signin({"username": "root", "password": "root"})
person = db.create("person", {"name": "Jane"})
print(person)
# File-based
with Surreal("file://mydb") as db:
db.use("test", "test")
db.signin({"username": "root", "password": "root"})
company = db.create("company", {"name": "TechStart"})
print(company)Use Embedded (memory, mem://, file://, or surrealkv://) when:
- Building desktop applications
- Running tests (in-memory is very fast)
- Local development without server setup
- Embedded systems or edge computing
- Single-application data storage
Use Remote (ws:// or http://) when:
- Multiple applications share data
- Distributed systems
- Cloud deployments
- Need horizontal scaling
- Centralized data management
For more examples, see the examples/embedded/ directory.
Multi-session and client-side transactions are supported only for WebSocket connections (ws:// or wss://). They are not available for HTTP or embedded connections.
- Sessions: Call
attach()on a WS connection to create a new session (returns aUUID). Usenew_session()to get anAsyncSurrealSessionorBlockingSurrealSessionthat scopes all operations to that session. Callclose_session()on the session (ordetach(session_id)on the connection) to drop it. - Transactions: On a session (or the default connection), call
begin_transaction()to start a transaction (returnsAsyncSurrealTransactionorBlockingSurrealTransaction). Run queries on the transaction object; then callcommit()orcancel()to finish.
Example (async WS):
from surrealdb import AsyncSurreal
async with AsyncSurreal("ws://localhost:8000/rpc") as db:
await db.signin({"username": "root", "password": "root"})
await db.use("test", "test")
session = await db.new_session()
await session.use("test", "test")
result = await session.query("SELECT 1")
txn = await session.begin_transaction()
await txn.query("CREATE person SET name = 'x'")
await txn.commit()
await session.close_session()On HTTP or embedded connections, attach(), detach(), begin(), commit(), cancel(), and new_session() raise NotImplementedError with a message that sessions/transactions are only supported for WebSocket connections.
Pydantic Logfire provides automatic instrumentation for SurrealDB operations, giving you instant observability into your database interactions. Logfire exports standard OpenTelemetry spans, making it compatible with any observability platform.
Install Logfire using pip:
pip install logfireOr install using uv:
uv add logfireEnable instrumentation:
import logfire
from surrealdb import AsyncSurreal
# Configure Logfire
logfire.configure()
# Instrument all SurrealDB operations
logfire.instrument_surrealdb()
# All database operations are now automatically traced
async with AsyncSurreal("ws://localhost:8000") as db:
await db.signin({"username": "root", "password": "root"})
await db.use("test", "test")
# These operations will appear as spans in your traces
await db.create("person", {"name": "Alice"})
await db.query("SELECT * FROM person")- Automatic tracing: All database methods are instrumented automatically
- Smart parameter logging: Sensitive data (tokens, passwords) are automatically scrubbed
- OpenTelemetry compatible: Works with Jaeger, DataDog, Honeycomb, and other OTel platforms
- Minimal overhead: Efficient instrumentation with negligible performance impact
- Works with all connection types: HTTP, WebSocket, and embedded databases
For a complete example with configuration options and best practices, see examples/logfire/.
Contributions to this library are welcome! If you encounter issues, have feature requests, or want to make improvements, feel free to open issues or submit pull requests.
If you want to contribute to the Github repo please read the general contributing guidelines on concepts such as how to create a pull requests here.
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.