Install the PocketBase Python SDK
masterInstall the SDK using pip to use it in your Python projects.
python3 -m pip install pocketbaserepository·master·Indexed 19 days ago
https://github.com/vaphes/pocketbaseA Python client SDK for the PocketBase backend providing a pythonic interface using HTTPX. It includes features for user and admin authentication, CRUD operations on collections, file uploads, and a BatchService for atomic operations. The SDK provides specialized services for backups, logs, health, settings, and cron jobs, and includes a filter() method for safe PocketBase filter string construction.
Install the SDK using pip to use it in your Python projects.
python3 -m pip install pocketbaseThe Client class supports intercepting requests and responses via two callback properties:
before_send: A callable that accepts (path: str, req_config: dict) and returns a tuple of (new_path, new_req_config). Use this to modify requests before they are dispatched.after_send: A callable that accepts (response: httpx.Response, data: Any, req_config: dict) and returns data. Use this to post-process the parsed JSON response.Note: These hooks are useful for global logging, custom header injection, or data transformation.
By default, the SDK converts API camelCase keys to Pythonic snake_case. If you want to keep the original key names from the PocketBase API, initialize the client with auto_snake_case=False.
from pocketbase import Client
# Fields will keep their original names from the API
client = Client(auto_snake_case=False)BaseAuthStore is an abstract base class intended to be extended for different authentication storage implementations (e.g., in-memory, file-based, or database-backed). When implementing a custom store, you can leverage the built-in logic for token management, record retrieval, and change listeners.When a real-time event is triggered, the callback receives a MessageData dataclass. This object encapsulates the change event sent by the PocketBase server.
Fields:
action: A str representing the type of change (e.g., create, update, delete).record: A pocketbase.models.record.Record object representing the state of the record involved in the event.@dataclasses.dataclass
class MessageData:
action: str
record: RecordTo use the PocketBase Python SDK, instantiate the Client class. You can provide a base_url, a language preference, and an auth_store for managing authentication. The client uses httpx internally for requests. By default, auto_snake_case is enabled, which maps API fields to Pythonic snake_case.
Key arguments:
base_url: The URL of your PocketBase instance.lang: Language code (default: en-US).auth_store: An object implementing AuthStoreProtocol to manage tokens.auto_snake_case: Boolean to automatically convert API field names to snake_case (default: True).from pocketbase import Client
pb = Client(base_url='https://your-pocketbase-url.com')The SSEClient provides a high-level interface for subscribing to Server-Sent Events (SSE). It runs an event loop in a background daemon thread, allowing your main application to continue executing while listening for specific event types.
To use it:
SSEClient with the target URL and optional headers/payload.add_event_listener(event_name, callback) to register a function that will be called whenever an event of that type is received.Event object containing the id, event type, data string, and optional retry value.from pocketbase.services.sse import SSEClient
def on_message(event):
print(f"Received event: {event.data}")
client = SSEClient(url="http://your-pocketbase-url/api/realtime")
client.add_event_listener("message", on_message)
# The client runs in the background. Keep your main thread alive.
import time
time.sleep(60)The BatchService allows you to queue multiple API operations (create, update, delete, upsert) and send them to the PocketBase /api/batch endpoint in a single HTTP request. This is more efficient than sending individual requests for every operation.
To use it:
BatchService with your client..collection(id_or_name) to get a SubBatchService for a specific collection..create(), .update(), or .delete() on the SubBatchService to queue operations..send() on the BatchService to execute all queued requests and receive a list of BatchRequestResult objects.# Assuming 'client' is an initialized PocketBase client
batch = BatchService(client)
# Queue a create and an update for the 'posts' collection
posts = batch.collection('posts')
posts.create(body_params={'title': 'Hello World'})
posts.update(record_id='REC_ID_123', body_params={'title': 'Updated Title'})
# Execute the batch
results = batch.send()
for result in results:
print(f"Status: {result['status_code']}")To create a record with file uploads, use the create method on a collection. For file fields, wrap the file data in a FileUpload object. The FileUpload constructor expects a tuple containing the filename and a file-like object (e.g., from open()).
from pocketbase import PocketBase
from pocketbase.client import FileUpload
client = PocketBase('http://127.0.0.1:8090')
# create record and upload file to image field
result = client.collection("example").create(
{
"status": "true",
"image": FileUpload(("image.png", open("image.png", "rb"))),
})To authenticate a regular user, use the auth_with_password method on a specific collection (typically the users collection). The returned object contains user data and allows you to check if the token is still valid using the .is_valid property.
from pocketbase import PocketBase
client = PocketBase('http://127.0.0.1:8090')
# authenticate as regular user
user_data = client.collection("users").auth_with_password(
"user@example.com", "0123456789")
# check if user token is valid
print(user_data.is_valid)To authenticate as an administrator, use the auth_with_password method on the client.admins service. The returned object allows you to check token validity via the .is_valid property.
from pocketbase import PocketBase
client = PocketBase('http://127.0.0.1:8090')
# or as admin
admin_data = client.admins.auth_with_password("test@example.com", "0123456789")
# check if admin token is valid
print(admin_data.is_valid)Use client.collection("collection_name").get_list(page, perPage, filter) to retrieve a paginated list of records. The filter parameter accepts a string following PocketBase filter syntax.
# list and filter "example" collection records
result = client.collection("example").get_list(
1, 20, {"filter": 'status = true && created > "2022-08-01 10:00:00"'}
)