PocketBase Python SDK

repository·master·Indexed 19 days ago

https://github.com/vaphes/pocketbase

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

Tokens
10.1K
Snippets
48
Records
57
Agent score
68%

What's inside pocketbase

  1. Use middleware with `before_send` and `after_send` hooks

    master

    The Client class supports intercepting requests and responses via two callback properties:

    1. 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.
    2. 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.

  2. Disable automatic snake_case conversion

    master

    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)
  3. Implement a custom AuthStore using BaseAuthStore

    master
    The 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.
  4. Understand the MessageData structure in real-time updates

    master

    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: Record
  5. Initialize the PocketBase Client

    master

    To 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')
  6. Use SSEClient to listen for real-time events

    master

    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:

    1. Initialize SSEClient with the target URL and optional headers/payload.
    2. Use add_event_listener(event_name, callback) to register a function that will be called whenever an event of that type is received.
    3. The callback receives an 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)
  7. Use BatchService to execute multiple requests in a single call

    master

    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:

    1. Initialize BatchService with your client.
    2. Use .collection(id_or_name) to get a SubBatchService for a specific collection.
    3. Call methods like .create(), .update(), or .delete() on the SubBatchService to queue operations.
    4. Call .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']}")
  8. Create a record and upload a file

    master

    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"))),
        })
  9. Authenticate as a regular user

    master

    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)
  10. Authenticate as an admin

    master

    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)
  11. List and filter collection records

    master

    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"'}
    )