• Start

Languages

Python

Connect to SurrealDB and run your first queries with the Python SDK.

The Python SDK for SurrealDB lets you connect to a database and query it from your application. This guide covers connecting, authenticating, and running your first queries.

Follow the installation guide to install the SDK as a dependency in your project. Once installed, import the SDK to start using it.

from surrealdb import Surreal

db = Surreal("ws://localhost:8000")

The Surreal and AsyncSurreal factory functions accept a connection URL and return the appropriate connection class based on the protocol.

You can use the .connect() method to open the connection, then .use() to select a namespace and database, and .signin() to authenticate.

Supported connection protocols include:

  • WebSocket (ws://, wss://) for long-lived stateful connections

  • HTTP (http://, https://) for short-lived stateless connections

  • Embedded (mem://, file://, surrealkv://) for in-process databases

from surrealdb import Surreal

db = Surreal("ws://localhost:8000")
db.connect()
db.use("company_name", "project_name")
db.signin({"username": "root", "password": "root"})

You can also use a context manager to automatically close the connection when you are done.

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

Once connected, you can use the .create() method to create records. Pass a table name or a RecordID as the first argument and the record data as the second.

from surrealdb import RecordID

user = db.create("users", {
    "name": "John",
    "email": "john@example.com",
    "age": 32,
})

product = db.create(RecordID("products", "apple"), {
    "name": "Apple",
    "price": 1.50,
    "category": "fruit",
})

The .select() method retrieves all records from a table, or a single record by its RecordID.

users = db.select("users")

apple = db.select(RecordID("products", "apple"))

For more advanced use cases, you can use the .query() method to run SurrealQL statements directly. Use the vars parameter to safely pass dynamic values.

result = db.query(
    "SELECT name, price FROM products WHERE price < $max_price ORDER BY price",
    {"max_price": 5.00},
)

Always close the connection when you are done to release resources. If you use a context manager, this happens automatically.

db.close()

You have learned how to install the SDK, connect to SurrealDB, create records, and retrieve data. There is a lot more you can do with the SDK, including updating and deleting records, authentication, live queries, and transactions.

Note

This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the Python SDK reference.

Was this page helpful?