Skip to main content

 

The official SurrealDB SDK for Python.


         

     

surrealdb.py

The official SurrealDB SDK for Python.

Documentation

How to install

# Using pip
pip install surrealdb

# Using uv
uv add surrealdb

Quick start

In 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.

Running SurrealDB

You can run SurrealDB locally or start with a free SurrealDB cloud account.

For local, two options:

  1. Install SurrealDB and run SurrealDB. Run in-memory with:
surreal start -u root -p root
  1. Run with Docker.
docker run --rm --pull always -p 8000:8000 surrealdb/surrealdb:latest start

Learn the basics

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

Embedded Database

SurrealDB can also run embedded directly within your Python application natively. This provides a fully-featured database without needing a separate server process.

Installation

The embedded database is included when you install surrealdb.

For source builds, you'll need Rust toolchain and maturin:

uv run maturin develop --release

In-Memory Database

Perfect 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())

File-Based Persistent Database

For persistent local storage:

import asyncio
from surrealdb import AsyncSurreal

async def main():
    # Create a file-based database (can use "file://", "surrealkv://", or "surrealkv+versioned://")
    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())

Blocking (Sync) API

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)

When to Use Embedded vs Remote

Use Embedded (memory, mem://, file://, surrealkv://, or surrealkv+versioned://) 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.

Sessions and transactions

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 a UUID). Use new_session() to get an AsyncSurrealSession or BlockingSurrealSession that scopes all operations to that session. Call close_session() on the session (or detach(session_id) on the connection) to drop it.
  • Transactions: On a session (or the default connection), call begin_transaction() to start a transaction (returns AsyncSurrealTransaction or BlockingSurrealTransaction). Run queries on the transaction object; then call commit() or cancel() 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.

Observability with Logfire

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.

Quick Start

Install Logfire using pip:

pip install logfire

Or install using uv:

uv add logfire

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

Features

  • 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

Learn More

For a complete example with configuration options and best practices, see examples/logfire/.

Contributing

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.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Metadata

Release files for surrealdb 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for surrealdb 2.0.0
File Size Uploaded
surrealdb-2.0.0.tar.gz 303.7 kB Details

Built distributions (wheels)

Table of built distributions (wheels) for surrealdb 2.0.0
File
surrealdb-2.0.0-cp39-abi3-win_amd64.whl CPython 3.9 abi3 Windows x86-64 Details
surrealdb-2.0.0-cp39-abi3-musllinux_1_2_x86_64.whl CPython 3.9 abi3 Linux musl 1.2+ x86-64 Details
surrealdb-2.0.0-cp39-abi3-musllinux_1_2_aarch64.whl CPython 3.9 abi3 Linux musl 1.2+ ARM64 Details
surrealdb-2.0.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl CPython 3.9 abi3 Linux glibc 2.17+ x86-64 Details
surrealdb-2.0.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl CPython 3.9 abi3 Linux glibc 2.17+ ARM64 Details
surrealdb-2.0.0-cp39-abi3-macosx_11_0_arm64.whl CPython 3.9 abi3 macOS 11.0+ ARM64 Details
surrealdb-2.0.0-cp39-abi3-macosx_10_12_x86_64.whl CPython 3.9 abi3 macOS 10.12+ x86-64 Details

Total release size: 38.9 MB

Release files / surrealdb-2.0.0.tar.gz

Download URL surrealdb-2.0.0.tar.gz
Size 303.7 kB
Tags Source
SHA-256 checksum
How to use checksums
70a2656bf5b6d844cf4c029d6e0a7309ca95b9ba282663f31c8b6e642fc8463a
BLAKE2b-256 checksum
How to use checksums
55b3231444479bd065b5d29c151296dd8aa4591f399039ffd39c45d1ea0b3906
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-win_amd64.whl

Download URL surrealdb-2.0.0-cp39-abi3-win_amd64.whl
Size 5.1 MB
Tags CPython 3.9 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
ba43f1156b2a6d00e8e595764505156db2f7fd5d023e189c59e9673fa9949fe8
BLAKE2b-256 checksum
How to use checksums
3c6b522f48258c2f1cefacfe55cb772e14e1c28b4973f63ba5baffc4998e9cc9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-musllinux_1_2_x86_64.whl

Download URL surrealdb-2.0.0-cp39-abi3-musllinux_1_2_x86_64.whl
Size 5.9 MB
Tags CPython 3.9 Linux musl 1.2+ x86-64 abi3
SHA-256 checksum
How to use checksums
e7163637c813e2e6daec7660c4d83462509c1c77ecb4086bdb3766af6fdfb571
BLAKE2b-256 checksum
How to use checksums
1da4d1259c9437e12bbe8e54416f610b9a4300791e655d8784e51c087394cce8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-musllinux_1_2_aarch64.whl

Download URL surrealdb-2.0.0-cp39-abi3-musllinux_1_2_aarch64.whl
Size 6.0 MB
Tags CPython 3.9 Linux musl 1.2+ ARM64 abi3
SHA-256 checksum
How to use checksums
d5dd4df823b407f58077a9dddc4f4bff938e365d091df56d2fe4108e980f8b87
BLAKE2b-256 checksum
How to use checksums
202e1d02a9c1d6cbeea1dae079320c7baaf89c0d465b204eaeb5fe8a543ee53a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

Download URL surrealdb-2.0.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Size 5.7 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64 abi3
SHA-256 checksum
How to use checksums
1e0d61545611cf86f13825932315e65c79a9f1bfb1c0fe3b40b0e48562b8673c
BLAKE2b-256 checksum
How to use checksums
4c55463e429e85e41c0941b3daa878b6005f76fcabaab9a09beab02d2852c4b3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl

Download URL surrealdb-2.0.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Size 5.8 MB
Tags CPython 3.9 Linux glibc 2.17+ ARM64 abi3
SHA-256 checksum
How to use checksums
e3a4e9c35964af1dc6ce01fe2aa553d6c3fcd0a8bd02c05e38fc88433395ba74
BLAKE2b-256 checksum
How to use checksums
181dd05be5d682b10ac8b2af74f93b374c43109585b7e6be3d9d2b4790960f20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-macosx_11_0_arm64.whl

Download URL surrealdb-2.0.0-cp39-abi3-macosx_11_0_arm64.whl
Size 5.0 MB
Tags CPython 3.9 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
8b0b24ea230a53ea6c67c51c8e45332d9383b4b8f42246b64c034a2b26d0cc2a
BLAKE2b-256 checksum
How to use checksums
d38c137e6d3e1ff0b2990dcf56c80920e2d64855ffdd16fe8195fa6c5c4adcf9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1

Release files / surrealdb-2.0.0-cp39-abi3-macosx_10_12_x86_64.whl

Download URL surrealdb-2.0.0-cp39-abi3-macosx_10_12_x86_64.whl
Size 5.1 MB
Tags CPython 3.9 abi3 macOS 10.12+ x86-64
SHA-256 checksum
How to use checksums
5ade2dfd53fedd7c7ddb3b102d6223ccefa30ad8a1df1cde261ce8004e97aa2f
BLAKE2b-256 checksum
How to use checksums
864785b04ef0224cb1538d8b0154a16c222e1e4174016ad3c7833e4b00cc6382
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via maturin/1.13.1
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page