Skip to main content

SurrealDB python client

Project description


 

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://" 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())

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://, 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.

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

surrealdb-2.0.0a1.tar.gz (303.3 kB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

surrealdb-2.0.0a1-cp39-abi3-win_amd64.whl (5.1 MB view details)

Uploaded CPython 3.9+Windows x86-64

surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_x86_64.whl (6.0 MB view details)

Uploaded CPython 3.9+musllinux: musl 1.2+ x86-64

surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_aarch64.whl (6.0 MB view details)

Uploaded CPython 3.9+musllinux: musl 1.2+ ARM64

surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (5.7 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.17+ x86-64

surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (5.8 MB view details)

Uploaded CPython 3.9+manylinux: glibc 2.17+ ARM64

surrealdb-2.0.0a1-cp39-abi3-macosx_11_0_arm64.whl (5.0 MB view details)

Uploaded CPython 3.9+macOS 11.0+ ARM64

surrealdb-2.0.0a1-cp39-abi3-macosx_10_12_x86_64.whl (5.2 MB view details)

Uploaded CPython 3.9+macOS 10.12+ x86-64

File details

Details for the file surrealdb-2.0.0a1.tar.gz.

File metadata

  • Download URL: surrealdb-2.0.0a1.tar.gz
  • Upload date:
  • Size: 303.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: maturin/1.12.4

File hashes

Hashes for surrealdb-2.0.0a1.tar.gz
Algorithm Hash digest
SHA256 dfaad00df394f2543489af7043bdf76cf3bffb5141e5703318fcc7b2bdf3cbfd
MD5 ef8ec235d58e3ed070c073d7e92b2f54
BLAKE2b-256 96cb3fef136a394b9530d9ca36da473b327fcb3de115970dd26cdf39ac65ef99

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-win_amd64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-win_amd64.whl
Algorithm Hash digest
SHA256 db95a3f491c0654e486673a7aa373c14e084ac9d0c9c087f4228b4054d96bcf5
MD5 d76c4910ca9a42f7cd5b324d2db8191e
BLAKE2b-256 bc179309e7fc6ef32c629d5ff83f248b489080b4ef74b5a13b823cf4c0a91276

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 e35193e33151aa79e4398afc57851de49c94fb06d261371f5991df994f9235af
MD5 b984156e5bea4d54d48b8fcc351cd108
BLAKE2b-256 227d7b4a471f4e7fc23ff4741a0ef4581c02b497506ef3d6de17191791fed004

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_aarch64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-musllinux_1_2_aarch64.whl
Algorithm Hash digest
SHA256 d7214c50de23e72c513a73289395d2ea74a26eb98e0054052da8dfa2b49b4345
MD5 cf1570748a106d2c6422fa5d651a243f
BLAKE2b-256 c4249201add9034efe83d32b13a960b0e7f49ebfba51f9da5b995620f5732551

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm Hash digest
SHA256 5ae9782e06229ef95d2c7f91757b61f0ed675469390f9e1ff545150d2cfb5fdb
MD5 731e4066d0de790e5a1f833c5a161c05
BLAKE2b-256 603a4affda30fd24bf940145ba8779252d1fe16ab466792d2d4a5dcded3ca467

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm Hash digest
SHA256 a3cb34e74cc3f2554e61d9c63d398c8d70c6fb87ca91ce8e721679465a3a8302
MD5 2ee805e8fa8c93c290e826efbeca5870
BLAKE2b-256 f1a6ea4cbad8f790886b4582475eb555caf55449688057a890b7759737f555fd

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-macosx_11_0_arm64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-macosx_11_0_arm64.whl
Algorithm Hash digest
SHA256 45d7c4c5f20598481eeff5e38f48f97b91c5e700b08bc629eb87bbd1bd9fb062
MD5 417c435edf3ef35b4d1bfd7b53e65a4e
BLAKE2b-256 c53e7d463cbc1a75e47c79246928b7729722f8ef6701040139f6f0bf1bccde1e

See more details on using hashes here.

File details

Details for the file surrealdb-2.0.0a1-cp39-abi3-macosx_10_12_x86_64.whl.

File metadata

File hashes

Hashes for surrealdb-2.0.0a1-cp39-abi3-macosx_10_12_x86_64.whl
Algorithm Hash digest
SHA256 7507d2b5ac661ab4b78081526ea1fb654a9f455201fc6cef8f7026a03f3ce8f6
MD5 edc53fc17c680cf76b9ed681d9bf87b2
BLAKE2b-256 f1ab131de62bd353c91a4c686b90ee4a509f4f63d53b42637d7f8172b1009e7d

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page