Skip to content

API Reference

/

Python Types

Python types

This page lists the type aliases, dataclasses and constants that the Python SDK exports for annotating and configuring your code. They cover the Value union, the record ID unions, authentication tokens, connection aliases and options, request and response types, and the server versions that the SDK supports. The value classes, such as RecordID and Duration, have their own pages under Python values.

Source: types.py, features.py, url.py, reconnect.py

Value is the union of every value that the SDK sends to SurrealDB or reads back. Methods use it to annotate record data, query variables and results.

Type definition
Value = (
    str | int | float | bool | None | NullType
    | bytes | UUID | Decimal
    | Table | Range | RecordID | StringRecordId | File
    | Duration | Datetime
    | BigDecimal | PlainDate | PlainTime | Timestamp | Interval | Regex
    | date | time
    | GeometryPoint | GeometryLine | GeometryPolygon
    | GeometryMultiPoint | GeometryMultiLine | GeometryMultiPolygon
    | GeometryCollection
    | SurrealSet | set[Any] | frozenset[Any]
    | dict[str, "Value"] | list["Value"]
)

The union is recursive: a dict or a list can hold any Value. Some members are covered without being named. A datetime.datetime, and so a PreciseDatetime, is a subclass of date, and the sized numbers such as U8 and F32 are subclasses of int and float. A set or a frozenset is only sent: a set reads back as a SurrealSet. The SDK sends the SurrealDB 4.0 types, from BigDecimal to time, as their own types only over cbor.2. The Value types page shows what each member becomes.

RecordIdValue is the union of the ID types that SurrealDB accepts in a record ID. The RecordID constructor checks its ID against this union, so use it to annotate an ID that you build.

Type definition
RecordIdValue = (
    str | int | uuid.UUID
    | list[Any] | tuple[Any, ...] | dict[str, Any]
    | Range
)

RecordID.id is typed as Value rather than RecordIdValue, because a record ID read from the server can hold any value the server sends.

RecordIdType is the union that CRUD methods accept as a target. It is not exported from surrealdb; import it from surrealdb.data.types.record_id.

Type definition
RecordIdType = str | RecordID | StringRecordId | Table

A str is always a table name, the same as a Table. Pass a RecordID or a StringRecordId to target one record.

Tokens is the frozen dataclass that signin(), signup() and refresh() return. It holds the access token, and a refresh token when the access method is defined WITH REFRESH.

Type definition
@dataclass(frozen=True)
class Tokens:
    access: str | None = None
    refresh: str | None = None
FieldTypeDescription
accessstr | NoneThe access token, a JWT.
refreshstr | NoneThe refresh token, or None when the access method has none.

repr() shows '<redacted>' in place of each token, so a Tokens value is safe to log. Pass the value itself to refresh(), revoke() or the auth= option of a connection, and its access token to authenticate().

from surrealdb import Surreal

with Surreal("ws://localhost:8000") as db:
    tokens = db.signin({"username": "root", "password": "secret"})
    print(tokens)
    print(tokens.access is not None, tokens.refresh)
Output
Tokens(access='<redacted>', refresh=None)
True None

These two type aliases describe the connection objects that Surreal() and AsyncSurreal() return. Those two names are factory functions, so they cannot annotate a variable or a parameter. Use these unions instead.

Type definition
BlockingSurrealConnection = (
    BlockingWsSurrealConnection
    | BlockingHttpSurrealConnection
    | BlockingEmbeddedSurrealConnection
)
AsyncSurrealConnection = (
    AsyncWsSurrealConnection
    | AsyncHttpSurrealConnection
    | AsyncEmbeddedSurrealConnection
)

Without the embedded extra, the embedded classes do not exist, and the unions at run time hold only the websocket and HTTP classes.

from surrealdb import AsyncSurreal, AsyncSurrealConnection

async def open_connection(url: str) -> AsyncSurrealConnection:
    db = AsyncSurreal(url)
    await db.connect()
    return db

UrlScheme is an enum of the URL schemes that Surreal() and AsyncSurreal() accept. The scheme of the URL decides the class of the connection.

Type definition
class UrlScheme(Enum):
    HTTP = "http"
    HTTPS = "https"
    WS = "ws"
    WSS = "wss"
    MEM = "mem"
    FILE = "file"
    MEMORY = "memory"
    SURREALKV = "surrealkv"
    SURREALKV_VERSIONED = "surrealkv+versioned"
MembersConnectionDescription
WS, WSSWebSocketA long-lived connection with every feature, including live queries, sessions and transactions.
HTTP, HTTPSHTTPA connection with no persistent socket.
MEM, MEMORYEmbeddedAn in-memory database. Needs the embedded extra.
FILE, SURREALKVEmbeddedA database stored on disk. Needs the embedded extra.
SURREALKV_VERSIONEDEmbeddedA database stored on disk that keeps earlier versions of each record, for SELECT ... VERSION. Needs the embedded extra.

memory also works on its own, with no ://. Any other scheme raises UnsupportedEngineError. See URL schemes for the full forms of each URL.

ReconnectOptions is a frozen dataclass that sets how a websocket connection reconnects after the socket drops. Pass it as the reconnect= option of Surreal() or AsyncSurreal(). reconnect=True, the default, uses ReconnectOptions(), and reconnect=False turns reconnecting off.

FieldTypeDefaultDescription
enabledboolTrueWhether to reconnect at all.
attemptsint5The number of attempts before the connection gives up, or -1 for no limit.
retry_delayfloat1.0The base wait, in seconds.
retry_delay_maxfloat60.0The longest wait between attempts, in seconds.
retry_delay_multiplierfloat2.0The factor that each wait is multiplied by for the next attempt.
retry_delay_jitterfloat0.1The fraction of each wait, from 0 to 1, by which the wait changes at random, so that many clients do not reconnect at the same moment.

The wait before attempt n is retry_delay * retry_delay_multiplier ** n seconds, up to retry_delay_max. An invalid value raises TypeError or ValueError when the options are made.

from surrealdb import ReconnectOptions, Surreal

db = Surreal(
    "ws://localhost:8000",
    reconnect=ReconnectOptions(attempts=-1, retry_delay_max=10.0),
)

ApiResponse is the frozen dataclass that api() returns. It holds the answer of an endpoint defined with DEFINE API, which needs SurrealDB 3.0 or later.

Field or propertyTypeDescription
statusintThe HTTP status code.
bodyValueThe body of the response. Defaults to None.
headersdict[str, str]The response headers.
okboolProperty. Whether status is from 200 to 299.
from surrealdb import Surreal

with Surreal("ws://localhost:8000") as db:
    db.signin({"username": "root", "password": "secret"})
    db.use("surrealdb", "docs")

    db.query("""
        DEFINE API OVERWRITE "/greet" FOR get THEN {
            { status: 200, body: { hello: "world" } }
        };
    """).execute()

    response = db.api("/greet")
    print(response.ok, response.status, response.body)
Output
True 200 {'hello': 'world'}

ExportOptions is a frozen dataclass that chooses what export() and export_to() include. Every field defaults to None, which leaves the server's default.

FieldTypeDescription
users, accesses, params, functions, analyzers, records, sequencesbool | NoneWhether to include each kind of definition or data.
tablesbool | str | list[str] | dict | NoneTrue or False for every table, a table name or a list of them, or {"exclude": [...]} for every table except those.
versionsbool | NoneWhether to include earlier versions of records. SurrealDB 3.3.1 and later do not accept it, and the SDK raises UnsupportedFeatureError.

SurrealDB 2.0 takes no export options, so passing any raises UnsupportedFeatureError. See Import and export.

from surrealdb import ExportOptions, RecordID, Surreal

with Surreal("ws://localhost:8000") as db:
    db.signin({"username": "root", "password": "secret"})
    db.use("surrealdb", "docs")

    db.create(RecordID("person", "tobie"), {"name": "Tobie"})
    db.create(RecordID("post", 1), {"title": "Hello"})

    dump = db.export(ExportOptions(tables=["person"]))
    print("person:tobie" in dump, "post:1" in dump)
Output
True False

FileMetadata is a frozen dataclass with the fields file, size and updated, which describes one stored file. db.files.head() returns one, and db.files.list() returns a list of them. See File.

Note

surrealdb.data still defines Patch and QueryResponse, but no SDK method takes or returns either, and the SDK cannot send a Patch. Pass JSON Patch operations to .patch() as dicts, such as {"op": "replace", "path": "/age", "value": 37}.

These two constants give the range of SurrealDB versions that the SDK supports: from MINIMUM_VERSION, which is "2.0.0", up to but not including MAXIMUM_VERSION, which is "5.0.0". A remote connection asks the server for its version first, and refuses a server outside the range with UnsupportedVersionError. Pass version_check=False to connect anyway. A pre-release or nightly build counts as the release it leads to, so 5.0.0-alpha.1 is outside the range. Embedded connections are not checked.

Features lists the features that need a newer server than MINIMUM_VERSION. Pass one to db.is_feature_supported() to ask before you use it. A method that needs a feature the server does not have raises UnavailableFeatureError before anything is sent.

MemberNeeds SurrealDB
Features.LIVE_QUERIESEvery supported version
Features.SESSIONS3.0.0 or later
Features.API3.0.0 or later
Features.REFRESH_TOKENS3.0.0 or later
Features.TRANSACTIONS3.0.0 or later
Features.IMPORT_FAILURE_REPORTING3.1.0 or later
Features.QUERY_STREAMING3.3.0 or later

Feature is the frozen dataclass for one entry in Features.

Field or methodTypeDescription
namestrThe name of the feature, which str() also gives.
sincestr | NoneThe first version that has the feature, or None for every version.
untilstr | NoneThe first version that no longer has the feature, or None.
supports(version)boolWhether a server that reports version has the feature.
from surrealdb import Features

sessions = Features.SESSIONS
print(sessions, sessions.since)
print(sessions.supports("2.7.0"), sessions.supports("3.3.5"))
Output
sessions 3.0.0
False True

The streaming methods of a query builder give their own types, which are documented with the builders:

TypeGiven byReference
StatementResult.statements()Builders
ValueFrame, ErrorFrame, DoneFrame.stream()Builders
SyncRows, AsyncRows.rows()Builders

Was this page helpful?