### Get Connect URL: v0 SDK Examples Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md Shows how to obtain a connect URL in the v0 SDK, either for a new session or an existing one. ```python from browserbase import Browserbase browserbase = Browserbase(api_key=BROWSERBASE_API_KEY, project_id=BROWSERBASE_PROJECT_ID) # To create a new session and connect to it connect_url = browserbase.get_connect_url() # To connect to an existing session connect_url = browserbase.get_connect_url(session_id=some_session.id) ``` -------------------------------- ### Run Repository Examples Source: https://github.com/browserbase/sdk-python/blob/main/README.md Commands to synchronize dependencies and execute specific examples from the repository. ```bash rye sync rye run example playwright_basic # replace with the example you want to run ``` -------------------------------- ### Install SDK from git Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Install the repository directly from the remote git source. ```sh $ pip install git+ssh://git@github.com/browserbase/sdk-python.git ``` -------------------------------- ### Execute custom example script Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Make the example script executable and run it against the API. ```sh $ chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Install Browserbase SDK Source: https://github.com/browserbase/sdk-python/blob/main/README.md Install the pre-release version of the Browserbase Python library from PyPI. ```sh pip install '--pre browserbase' ``` -------------------------------- ### Install local wheel file Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Install the package using the generated wheel file. ```sh $ pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Install Browserbase Python SDK Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Shows the command to install the Browserbase Python SDK using pip. Also provides an alternative command for installing with the aiohttp backend. ```bash pip install browserbase ``` ```bash pip install 'browserbase[aiohttp]' ``` -------------------------------- ### Define custom example script Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Add a new executable Python script in the examples directory. ```py # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` -------------------------------- ### Run mock server Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Start the mock server required for running tests. ```sh $ ./scripts/mock ``` -------------------------------- ### Fetch API - Raw Output Example Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/fetch_api.md Example demonstrating the default 'raw' output format for the Fetch API, returning the response content as an HTML string. ```python response = client.fetch_api.create(url="https://example.com") # response.content is HTML string ``` -------------------------------- ### Install dependencies with pip Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Install development dependencies using the standard pip workflow. ```sh $ pip install -r requirements-dev.lock ``` -------------------------------- ### Fetch API - Markdown Output Example Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/fetch_api.md Example showing how to get the Fetch API response content as a markdown string. The content is converted from the page's HTML. ```python response = client.fetch_api.create( url="https://example.com/article", format="markdown" ) # response.content is markdown string with # Headers, **bold**, etc. ``` -------------------------------- ### Create Session: v1 SDK Basic Example Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md Demonstrates creating a session with the v1 Browserbase Python SDK using the `bb.sessions.create()` method. ```python from browserbase import Browserbase bb = Browserbase(api_key=BROWSERBASE_API_KEY) session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID, extension_id="some_extension_id") ``` -------------------------------- ### Async Web Search Example Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/search.md Demonstrates how to perform a web search asynchronously using AsyncBrowserbase and process the results. ```python import asyncio from browserbase import AsyncBrowserbase async def main(): async with AsyncBrowserbase(api_key="key") as client: response = await client.search.web( query="async python", num_results=10 ) for result in response.results: print(result.title) asyncio.run(main()) ``` -------------------------------- ### Async Fetch API Example Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/fetch_api.md Demonstrates how to use the asynchronous version of the Fetch API with `AsyncBrowserbase`. Requires an `api_key`. ```python import asyncio from browserbase import AsyncBrowserbase async def main(): async with AsyncBrowserbase(api_key="key") as client: response = await client.fetch_api.create( url="https://example.com", format="markdown" ) print(response.content) asyncio.run(main()) ``` -------------------------------- ### Create Session: v0 SDK Example Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md Shows how to create a session using the v0 Browserbase Python SDK, including the use of `CreateSessionOptions`. ```python from browserbase import Browserbase, CreateSessionOptions browserbase = Browserbase(api_key=BROWSERBASE_API_KEY, project_id=BROWSERBASE_PROJECT_ID) options = CreateSessionOptions(extensionId='123') browserbase.create_session(options) ``` -------------------------------- ### Example: Catch InternalServerError Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Shows how to catch an InternalServerError when creating a session. ```python from browserbase import InternalServerError try: session = client.sessions.create(project_id="proj-id") except InternalServerError as e: print("Server error, retrying...") ``` -------------------------------- ### Synchronous Client Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Demonstrates the basic setup for using the Browserbase SDK in a synchronous manner. ```python from browserbase import Browserbase client = Browserbase(api_key="key") session = client.sessions.create(project_id="proj-id") ``` -------------------------------- ### Create a Session Source: https://github.com/browserbase/sdk-python/blob/main/api.md Use the client.sessions.create method to start a new session. Pass parameters as keyword arguments. ```python client.sessions.create(**params) ``` -------------------------------- ### Example: Catch RateLimitError Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Demonstrates how to catch a RateLimitError when making multiple requests. ```python from browserbase import RateLimitError try: sessions = [client.sessions.create(project_id="proj") for _ in range(100)] except RateLimitError as e: print("Rate limited, back off and retry") ``` -------------------------------- ### Fetch API - JSON Output with Schema Example Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/fetch_api.md Example for fetching structured data using the Fetch API's JSON format. A JSON schema is provided to define the expected structure of the output. ```python schema = { "type": "object", "properties": { "title": {"type": "string"}, "description": {"type": "string"}, "price": {"type": "number"} } } response = client.fetch_api.create( url="https://example.com/product", format="json", schema=schema ) # response.content is JSON string matching schema ``` -------------------------------- ### Configure Async Client with aiohttp Source: https://github.com/browserbase/sdk-python/blob/main/README.md Install the aiohttp dependency and configure the AsyncBrowserbase client to use it as the HTTP backend for improved concurrency. ```sh pip install '--pre browserbase[aiohttp]' ``` ```python import os import asyncio from browserbase import DefaultAioHttpClient from browserbase import AsyncBrowserbase async def main() -> None: async with AsyncBrowserbase( api_key=os.environ.get("BROWSERBASE_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: session = await client.sessions.create( project_id="your_project_id", ) asyncio.run(main()) ``` -------------------------------- ### Accessing Session Artifacts Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Provides examples for accessing various session artifacts, including logs, recordings, replays, downloads, and uploads. ```python # Logs logs = client.sessions.logs.list("session-id") # Recording recording = client.sessions.recording.retrieve("session-id") # Replay replay = client.sessions.replays.retrieve("session-id") # Downloads zip_file = client.sessions.downloads.list("session-id") # Uploads client.sessions.uploads.create("session-id", file=Path("test.pdf")) ``` -------------------------------- ### Sync dependencies with Rye Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Manually synchronize all features if Rye is already installed. ```sh $ rye sync --all-features ``` -------------------------------- ### Configure Asynchronous Client with Custom HTTP Client (aiohttp) Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Configure the asynchronous Browserbase client to use a custom `aiohttp.ClientSession` via `DefaultAioHttpClient`. This requires installing the `aiohttp` extra. ```python from browserbase import AsyncBrowserbase, DefaultAioHttpClient async with AsyncBrowserbase( http_client=DefaultAioHttpClient() ) as client: session = await client.sessions.create(project_id="proj-id") ``` -------------------------------- ### Get Session Recording (v0 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md This is the v0 SDK method for retrieving a session's recording. ```python # v0 SDK recording = browserbase.get_session_recording(session_id=some_session.id) ``` -------------------------------- ### Get Session Recording (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md The v1 SDK retrieves a session recording using `bb.sessions.recording.retrieve(id=...)`. ```python # v1 SDK recording = bb.sessions.recording.retrieve(id="some_session_id") ``` -------------------------------- ### Get Session (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md In the v1 SDK, retrieve a session by its ID using `bb.sessions.retrieve(id=...)`. ```python # v1 SDK session = bb.sessions.retrieve(id="some_session_id") ``` -------------------------------- ### Get Session Logs (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md In the v1 SDK, session logs are accessed via `bb.sessions.logs.list(id=...)`. ```python # v1 SDK logs = bb.sessions.logs.list(id="some_session_id") ``` -------------------------------- ### Configure aiohttp Client for Async Operations Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/configuration.md Use `DefaultAioHttpClient` for asynchronous operations with an aiohttp backend. Requires installing the 'aiohttp' extra. ```python from browserbase import DefaultAioHttpClient async with AsyncBrowserbase( http_client=DefaultAioHttpClient() ) as client: session = await client.sessions.create(project_id="proj-id") ``` -------------------------------- ### Get Session Downloads (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md In the v1 SDK, session downloads are retrieved with `bb.sessions.downloads.retrieve(id=...)`. Default retries can be configured during Browserbase initialization. ```python # v1 SDK downloads = bb.sessions.downloads.retrieve(id="some_session_id") ``` -------------------------------- ### Configuring the Browserbase Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Illustrates how to initialize the Browserbase client with various configuration options like API key, base URL, timeout, max retries, and custom headers. Also shows how to override settings for a single request. ```python import httpx client = Browserbase( api_key="key", base_url="https://api.browserbase.com", timeout=60.0, max_retries=2, default_headers={"X-Custom": "value"}, http_client=None, # Custom httpx.Client ) # Per-request override session = client.with_options(timeout=5.0).sessions.create( project_id="proj-id" ) ``` -------------------------------- ### FileTypes for Uploads Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/types.md Provides examples of different data types that can be used as file inputs for uploads, including bytes, `Path` objects, file handles, and tuples for filename, content, and MIME type. Imports `Path` from `pathlib` and `os`. ```python from pathlib import Path import os # All these are FileTypes: file1 = b"file content" file2 = Path("file.zip") file3 = open("file.zip", "rb") file4 = ("filename.zip", b"content", "application/zip") ``` -------------------------------- ### Create or Retrieve Session Connect URL (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md Use this function to get a connect URL for an existing session or create a new one if no session ID is provided. Requires Browserbase SDK initialization with an API key and project ID. ```python from browserbase import Browserbase bb = Browserbase(api_key=BROWSERBASE_API_KEY) def get_connect_url(bb: Browserbase, session_id: str = None): """ Retrieve a connect url for a given session or create a new one. If a session id is provided, retrieve the connect url for the existing session. Otherwise, create a new session and return the connect url. """ if session_id: session = bb.sessions.retrieve(id=session_id) else: session = bb.sessions.create(project_id=BROWSERBASE_PROJECT_ID) return session.connect_url connect_url = get_connect_url(bb, session_id="some_session_id") ``` -------------------------------- ### Build package from source Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Create a distributable wheel and source distribution. ```sh $ rye build # or $ python -m build ``` -------------------------------- ### Determine Installed Browserbase SDK Version Source: https://github.com/browserbase/sdk-python/blob/main/README.md Check the installed version of the Browserbase SDK at runtime by importing the library and accessing the `__version__` attribute. ```python import browserbase print(browserbase.__version__) ``` -------------------------------- ### Import Browserbase and ContextsResource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/contexts.md Import necessary classes from the browserbase SDK and initialize the client. ```python from browserbase import Browserbase from browserbase.resources.contexts import ContextsResource client = Browserbase() contexts = client.contexts # ContextsResource ``` -------------------------------- ### Update Session Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Updates an existing session, for example, to release it. ```APIDOC ## POST /v1/sessions/{id} ### Description Updates an existing session, for example, to release it. ### Method POST ### Endpoint /v1/sessions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Session ID #### Request Body - **status** (string) - Required - Set to `REQUEST_RELEASE` to release the session. - **project_id** (string) - Required - Project ID ### Response #### Success Response (200) - **Session object** - The updated session object. ``` -------------------------------- ### Example: Catch APITimeoutError Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Demonstrates catching an APITimeoutError when a request times out. ```python from browserbase import APITimeoutError try: session = client.sessions.create(project_id="proj-id") except APITimeoutError as e: print("Request timed out") ``` -------------------------------- ### Create Session: v1 SDK with BrowserSettings Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md Illustrates advanced session creation in the v1 SDK using `BrowserSettings` and Pydantic's `TypeAdapter` for complex configurations. ```python from browserbase import Browserbase from pydantic import TypeAdapter from browserbase.types.session_create_params import BrowserSettings session = bb.sessions.create( project_id=BROWSERBASE_PROJECT_ID, extension_id="some_extension_id", browser_settings=TypeAdapter(BrowserSettings).validate_python( {"context": {"id": context_id, "persist": True}} ), ) ``` -------------------------------- ### Initialize Browserbase Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Instantiate the Browserbase client with your API key. This is the primary entry point for SDK interactions. ```python from browserbase import Browserbase client = Browserbase(api_key="your-api-key") ``` -------------------------------- ### Debug Session Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions.md Gets live debugging URLs for a specific session. ```APIDOC ## GET /sessions/{id}/debug ### Description Gets live debugging URLs for a session. ### Method GET ### Endpoint /sessions/{id}/debug ### Parameters #### Path Parameters - **id** (str) - Yes - Session ID ### Response #### Success Response (200) - (SessionLiveURLs) - Object with debugging/inspection URLs. ### Request Example ```python urls = client.sessions.debug("session-id-123") print(urls) ``` ``` -------------------------------- ### Initialize Synchronous Browserbase Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/configuration.md Instantiate the synchronous Browserbase client with various configuration options. ```python from browserbase import Browserbase client = Browserbase( api_key="your-api-key", base_url="https://api.browserbase.com", timeout=60.0, max_retries=2, default_headers=None, default_query=None, http_client=None, _strict_response_validation=False, ) ``` -------------------------------- ### Example: Catch APIConnectionError Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Illustrates catching an APIConnectionError and accessing its message and cause. ```python from browserbase import APIConnectionError try: session = client.sessions.create(project_id="proj-id") except APIConnectionError as e: print(f"Connection error: {e.message}") print(f"Underlying cause: {e.__cause__}") ``` -------------------------------- ### Import Browserbase SDK and Initialize Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions.md Import the necessary classes from the Browserbase SDK and initialize the client. The sessions attribute provides access to the SessionsResource. ```python from browserbase import Browserbase from browserbase.resources.sessions import SessionsResource client = Browserbase() sessions = client.sessions # SessionsResource ``` -------------------------------- ### Example: Catch APIResponseValidationError Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Illustrates catching APIResponseValidationError when strict response validation is enabled. ```python client = Browserbase(api_key="key", _strict_response_validation=True) try: session = client.sessions.create(project_id="proj-id") except APIResponseValidationError as e: print(f"Invalid response data: {e.message}") print(f"Status: {e.status_code}") ``` -------------------------------- ### Initialize Synchronous Browserbase Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Instantiate the synchronous Browserbase client. Provide your API key directly or rely on the BROWSERBASE_API_KEY environment variable. ```python from browserbase import Browserbase client = Browserbase(api_key="your-api-key") # Or use environment variable client = Browserbase() ``` -------------------------------- ### Replays retrieve Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Gets replay metadata for the entire session, including page information. ```APIDOC ## GET /sessions/{id}/replays ### Description Gets replay metadata for entire session. ### Method GET ### Endpoint /sessions/{id}/replays ### Parameters #### Path Parameters - **id** (str) - Yes - Session ID ### Response #### Success Response (200) - **pages** (List[PageInfo]) - Array of pages visited in session ### Request Example ```python response = client.sessions.replays.retrieve("session-id-123") ``` ``` -------------------------------- ### Browserbase Configuration Methods Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Provides methods to create new client instances with optional configuration overrides, useful for per-request settings. ```APIDOC ## Configuration Methods ### copy Creates a new client instance with optional overrides. Useful for per-request configuration. ```python def copy( *, api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, max_retries: int | NotGiven = not_given, default_headers: Mapping[str, str] | None = None, set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, _extra_kwargs: Mapping[str, Any] = {} ) -> Browserbase ``` #### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | api_key | str \| None | None | API key for authentication. If not provided, reads from `BROWSERBASE_API_KEY` environment variable. | | base_url | str \| httpx.URL \| None | API endpoint URL. Can be overridden via `BROWSERBASE_BASE_URL` environment variable. | | timeout | float \| Timeout \| None \| NotGiven | not_given | Request timeout in seconds. Defaults to 60 seconds. | | max_retries | int \| NotGiven | not_given | Maximum number of retries for failed requests. | | default_headers | Mapping[str, str] \| None | None | Additional HTTP headers to include with every request. | | set_default_headers | Mapping[str, str] \| None | None | Headers to set for the new client instance, overriding existing ones. | | default_query | Mapping[str, object] \| None | None | Additional query parameters to include with every request. | | set_default_query | Mapping[str, object] \| None | None | Query parameters to set for the new client instance, overriding existing ones. | | _extra_kwargs | Mapping[str, Any] | {} | Additional keyword arguments to pass to the client constructor. | #### Returns - `Browserbase`: A new client instance with the specified overrides. ``` -------------------------------- ### Create New Client Instance with Overrides Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Use the `copy` method to create a new client instance with modified configuration, such as API key, base URL, or timeout. ```python new_client = client.copy(timeout=30.0, default_headers={"X-Custom-Header": "value"}) ``` -------------------------------- ### Recording retrieve Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Gets session recording metadata, including HLS stream URL. ```APIDOC ## GET /sessions/{id}/recording ### Description Gets session recording metadata. ### Method GET ### Endpoint /sessions/{id}/recording ### Parameters #### Path Parameters - **id** (str) - Yes - Session ID ### Response #### Success Response (200) - **hls_url** (str) - HLS stream URL for playback - **duration** (int) - Recording duration in seconds ### Request Example ```python recording = client.sessions.recording.retrieve("session-id-123") print(f"Recording: {recording.hls_url}") print(f"Duration: {recording.duration}s") ``` ``` -------------------------------- ### Configure Async httpx Client with Browserbase Defaults Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/configuration.md Utilize `DefaultAsyncHttpxClient` for asynchronous operations, configuring the `httpx.AsyncClient` with proxy settings. ```python from browserbase import DefaultAsyncHttpxClient import httpx async with AsyncBrowserbase( http_client=DefaultAsyncHttpxClient( proxy="http://proxy.example.com:8080" ) ) as client: session = await client.sessions.create(project_id="proj-id") ``` -------------------------------- ### ExtensionsResource.retrieve Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/extensions.md Gets an extension by its ID. This allows retrieving details of an already uploaded extension. ```APIDOC ## GET /extensions/{id} ### Description Gets an extension by its ID. This allows retrieving details of an already uploaded extension. ### Method GET ### Endpoint /extensions/{id} ### Parameters #### Path Parameters - **id** (str) - Required - Extension ID ### Response #### Success Response (200) - **id** (str) - Extension ID (use in sessions) - **file_name** (str) - Uploaded filename - **project_id** (str) - Project the extension belongs to - **created_at** (datetime) - Upload timestamp - **updated_at** (datetime) - Last update timestamp #### Response Example ```json { "id": "ext-abcdef123456", "file_name": "my-extension.zip", "project_id": "proj-abcdef123456", "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Session Logs (v0 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md This is the v0 SDK method for retrieving session logs. ```python # v0 SDK logs = browserbase.get_session_logs(session_id=some_session.id) ``` -------------------------------- ### Import Browserbase Client and Recording Sub-resource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Initializes the Browserbase client and accesses the recording sub-resource for retrieving session recording metadata. ```python client = Browserbase() recording = client.sessions.recording ``` -------------------------------- ### Instantiate Client with Inline Options Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Use the `with_options` alias for `copy()` to apply options like timeout for inline usage when creating sessions. ```python session = client.with_options(timeout=10).sessions.create(project_id="proj-id") ``` -------------------------------- ### Import Browserbase Client and Downloads Sub-resource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Initializes the Browserbase client and accesses the downloads sub-resource for retrieving session artifacts. ```python from browserbase import Browserbase client = Browserbase() downloads = client.sessions.downloads ``` -------------------------------- ### Update Session SDK Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this snippet to update a session's status, for example, to release it. ```python session = client.sessions.update("session-id", status="REQUEST_RELEASE") ``` -------------------------------- ### Get Project Usage Source: https://github.com/browserbase/sdk-python/blob/main/api.md Use the client.projects.usage method to retrieve usage statistics for a specific project by its ID. ```python client.projects.usage(id) ``` -------------------------------- ### Import Browserbase Client and Replays Sub-resource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Initializes the Browserbase client and accesses the replays sub-resource for retrieving session replay data. ```python client = Browserbase() replays = client.sessions.replays ``` -------------------------------- ### Run test suite Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Execute the project test suite. ```sh $ ./scripts/test ``` -------------------------------- ### Get Session (v0 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md This is the v0 SDK method for retrieving a specific session using its ID. ```python # v0 SDK session = browserbase.get_session(session_id="some_session_id") ``` -------------------------------- ### Create a New Extension Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Upload and create a new extension by providing a ZIP file. The SDK handles file uploads. ```python extension = client.extensions.create(file=Path("extension.zip")) ``` -------------------------------- ### Create Session Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Creates a new browser session. This is the primary method for starting an automated browsing session. ```APIDOC ## POST /v1/sessions ### Description Creates a new browser session. This is the primary method for starting an automated browsing session. ### Method POST ### Endpoint /v1/sessions ### Parameters #### Request Body - **browser_settings** (object) - Browser configuration - **extension_id** (string) - Extension to load - **keep_alive** (boolean) - Keep alive after disconnection - **project_id** (string) - Project ID - **proxies** (boolean | array) - Proxy configuration - **region** (string) - Region (us-west-2, us-east-1, eu-central-1, ap-southeast-1) - **api_timeout** (integer) - Session timeout in seconds - **user_metadata** (object) - Custom metadata ### Response #### Success Response (200) - **id** (string) - Session ID - **connectUrl** (string) - WebSocket URL to connect to the session - **seleniumRemoteUrl** (string) - Selenium remote control URL - **signingKey** (string) - Key for signing requests - **status** (string) - Current status of the session (e.g., PENDING, RUNNING) - **region** (string) - The region where the session is hosted - **projectId** (string) - The project ID associated with the session - **createdAt** (string) - Timestamp when the session was created - **expiresAt** (string) - Timestamp when the session will expire - **startedAt** (string) - Timestamp when the session started - **updatedAt** (string) - Timestamp when the session was last updated - **keepAlive** (boolean) - Indicates if the session should remain alive after disconnection - **proxyBytes** (integer) - Amount of proxy data used - **userMetadata** (object) - Custom metadata associated with the session ### Request Example ```json { "project_id": "proj-id" } ``` ### Response Example ```json { "id": "session-id", "connectUrl": "wss://...", "seleniumRemoteUrl": "http://...", "signingKey": "...", "status": "PENDING", "region": "us-west-2", "projectId": "proj-id", "createdAt": "2024-01-01T00:00:00Z", "expiresAt": "2024-01-01T01:00:00Z", "startedAt": "2024-01-01T00:00:00Z", "updatedAt": "2024-01-01T00:00:00Z", "keepAlive": false, "proxyBytes": 0, "userMetadata": {} } ``` ``` -------------------------------- ### create Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions.md Creates a new browser session with specified settings, proxy configurations, and metadata. ```APIDOC ## POST /sessions ### Description Creates a new browser session. Sessions provide isolated browser environments with support for proxies, extensions, recording, and more. ### Method POST ### Endpoint /sessions ### Parameters #### Query Parameters - **project_id** (str) - Optional - Project ID. If omitted, inferred from API key. - **region** (Literal["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"]) - Optional - Region for session execution - **api_timeout** (int) - Optional - Session timeout in seconds (defaults to project's defaultTimeout) #### Request Body - **browser_settings** (BrowserSettings) - Optional - Browser configuration (stealth mode, viewport, context, etc.) - **extension_id** (str) - Optional - Uploaded extension ID to load in the session - **keep_alive** (bool) - Optional - Keep session alive after disconnections (Hobby plan+) - **proxies** (Union[Iterable[ProxiesUnionMember0], bool]) - Optional - Proxy configuration. `true` for default, or array of proxy configs. - **user_metadata** (Dict[str, object]) - Optional - Arbitrary metadata to attach to session ### Request Example ```json { "project_id": "proj-123", "region": "us-west-2", "browser_settings": { "block_ads": true, "solve_captchas": true, "record_session": true }, "user_metadata": { "test_id": "123", "user_id": "abc" } } ``` ### Response #### Success Response (200) - **id** (str) - Session ID - **connect_url** (str) - WebSocket URL for connecting - **selenium_remote_url** (str) - HTTP URL for Selenium/CDP connections - **signing_key** (str) - Signing key for HTTP connections - All Session fields (status, region, created_at, etc.) #### Response Example ```json { "id": "sess-abc123xyz", "connect_url": "wss://connect.browserbase.com?signing_key=...", "selenium_remote_url": "http://compute.browserbase.com/sess-abc123xyz", "signing_key": "...", "status": "PENDING", "region": "us-west-2", "created_at": "2023-01-01T12:00:00Z" } ``` #### Error Handling - `BadRequestError`: Invalid parameters - `AuthenticationError`: Invalid API key - `APIStatusError`: API error ``` -------------------------------- ### Retrieve Session Replays SDK Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this snippet to get a list of pages captured during a session replay. ```python replay = client.sessions.replays.retrieve("session-id") ``` -------------------------------- ### Get Session Debug URLs SDK Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this snippet to retrieve debug URLs for a specific session. ```python urls = client.sessions.debug("session-id") ``` -------------------------------- ### Configure httpx Client with Browserbase Defaults Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/configuration.md Use `DefaultHttpxClient` to configure the underlying `httpx.Client` with proxy, local address, connection limits, and timeout. ```python from browserbase import DefaultHttpxClient import httpx client = Browserbase( http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", transport=httpx.HTTPTransport( local_address="0.0.0.0" ), limits=httpx.Limits( max_connections=50, max_keepalive_connections=20 ), timeout=httpx.Timeout(60.0) ) ) ``` -------------------------------- ### client.sessions.replays.retrieve Source: https://github.com/browserbase/sdk-python/blob/main/api.md Retrieves replays for a specific session. This method corresponds to the GET /v1/sessions/{id}/replays API endpoint. ```APIDOC ## GET /v1/sessions/{id}/replays ### Description Retrieves replay information for a specific session. ### Method GET ### Endpoint /v1/sessions/{id}/replays ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **replays** (ReplayRetrieveResponse) - Information about the session replays. ``` -------------------------------- ### Import Browserbase Client and Uploads Sub-resource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Initializes the Browserbase client and accesses the uploads sub-resource for uploading files into a session. ```python client = Browserbase() uploads = client.sessions.uploads ``` -------------------------------- ### client.sessions.recording.retrieve Source: https://github.com/browserbase/sdk-python/blob/main/api.md Retrieves the recording for a specific session. This method corresponds to the GET /v1/sessions/{id}/recording API endpoint. ```APIDOC ## GET /v1/sessions/{id}/recording ### Description Retrieves the recording data for a specific session. ### Method GET ### Endpoint /v1/sessions/{id}/recording ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **recording** (SessionRecording) - The session recording data. ``` -------------------------------- ### Import Browserbase Client and Logs Sub-resource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Initializes the Browserbase client and accesses the logs sub-resource for retrieving session logs. ```python client = Browserbase() logs = client.sessions.logs ``` -------------------------------- ### Retrieve Session Recording SDK Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this snippet to get the HLS URL and duration of a session's recording. ```python recording = client.sessions.recording.retrieve("session-id") ``` -------------------------------- ### Create an Extension Source: https://github.com/browserbase/sdk-python/blob/main/api.md Use the client.extensions.create method to add a new extension. Pass parameters as keyword arguments. ```python client.extensions.create(**params) ``` -------------------------------- ### client.sessions.logs.list Source: https://github.com/browserbase/sdk-python/blob/main/api.md Retrieves a list of logs for a specific session. This method corresponds to the GET /v1/sessions/{id}/logs API endpoint. ```APIDOC ## GET /v1/sessions/{id}/logs ### Description Retrieves a list of logs associated with a specific session. ### Method GET ### Endpoint /v1/sessions/{id}/logs ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **logs** (LogListResponse) - A list of session log objects. ``` -------------------------------- ### Instantiate Asynchronous Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Instantiate the asynchronous Browserbase client using an async context manager. This is the recommended way to manage the client's lifecycle in asynchronous applications. ```python import asyncio from browserbase import AsyncBrowserbase async def main(): async with AsyncBrowserbase(api_key="your-api-key") as client: session = await client.sessions.create(project_id="proj-id") print(session.id) asyncio.run(main()) ``` -------------------------------- ### Import Browserbase and ExtensionsResource Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/extensions.md Import necessary classes from the browserbase SDK to interact with the Extensions API. Instantiate the client and access the extensions resource. ```python from browserbase import Browserbase from browserbase.resources.extensions import ExtensionsResource client = Browserbase() extensions = client.extensions # ExtensionsResource ``` -------------------------------- ### Handle Raw HTTP Responses Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Use `with_raw_response` to get the raw httpx response object, including headers, before parsing. ```python response = client.sessions.with_raw_response.create(project_id="project-id") print(response.headers.get('X-My-Header')) session = response.parse() ``` -------------------------------- ### Get Debug Connection URLs (v0 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md This is the v0 SDK method for obtaining debug connection URLs for a session. ```python # v0 SDK debug_urls = browserbase.get_debug_connection_urls(session_id=some_session.id) ``` -------------------------------- ### Import Browserbase Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Import the synchronous and asynchronous Browserbase client classes. ```python from browserbase import Browserbase, AsyncBrowserbase ``` -------------------------------- ### Asynchronous Client Constructor Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Instantiate the asynchronous Browserbase client. Parameters are identical to the synchronous client. ```APIDOC ## Asynchronous Client: AsyncBrowserbase ### Constructor ```python AsyncBrowserbase( api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = 2, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.AsyncClient | None = None, _strict_response_validation: bool = False ) -> AsyncBrowserbase ``` Parameters are identical to the synchronous client. ### Usage ```python import asyncio from browserbase import AsyncBrowserbase async def main(): async with AsyncBrowserbase(api_key="your-api-key") as client: session = await client.sessions.create(project_id="proj-id") print(session.id) asyncio.run(main()) ``` ### Resource Properties Same as synchronous client, but all methods are async: - `sessions`: AsyncSessionsResource - `contexts`: AsyncContextsResource - `projects`: AsyncProjectsResource - `extensions`: AsyncExtensionsResource - `fetch_api`: AsyncFetchAPIResource - `search`: AsyncSearchResource ``` -------------------------------- ### Browserbase Constructor Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Initializes the synchronous Browserbase client. It supports authentication via API key, custom base URLs, timeouts, retries, default headers and query parameters, and allows for a custom httpx.Client instance. ```APIDOC ## Browserbase Constructor ### Description Initializes the synchronous Browserbase client. It supports authentication via API key, custom base URLs, timeouts, retries, default headers and query parameters, and allows for a custom httpx.Client instance. ### Method ```python Browserbase( api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = 2, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False ) -> Browserbase ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | api_key | str \| None | None | API key for authentication. If not provided, reads from `BROWSERBASE_API_KEY` environment variable. | | base_url | str \| httpx.URL \| None | https://api.browserbase.com | API endpoint URL. Can be overridden via `BROWSERBASE_BASE_URL` environment variable. | | timeout | float \| Timeout \| None \| NotGiven | not_given | Request timeout in seconds. Defaults to 60 seconds. | | max_retries | int | 2 | Maximum number of retries for failed requests. | | default_headers | Mapping[str, str] \| None | None | Additional HTTP headers to include with every request. | | default_query | Mapping[str, object] \| None | None | Additional query parameters to include with every request. | | http_client | httpx.Client \| None | None | Custom httpx.Client instance for HTTP requests. | | _strict_response_validation | bool | False | If True, raises APIResponseValidationError if response doesn't match schema. | ### Raises - `BrowserbaseError`: If `api_key` is not provided and `BROWSERBASE_API_KEY` environment variable is not set. ### Example ```python from browserbase import Browserbase client = Browserbase(api_key="your-api-key") # Or use environment variable client = Browserbase() ``` ``` -------------------------------- ### Create and Connect to a Browser Session Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/README.md Create a new browser session with optional project ID and browser settings. Obtain WebSocket or Selenium Remote URLs to connect. ```python session = client.sessions.create( project_id="proj-id", region="us-west-2", browser_settings={"block_ads": True} ) # Connect via WebSocket or HTTP ws_url = session.connect_url http_url = session.selenium_remote_url ``` -------------------------------- ### Bootstrap development environment with Rye Source: https://github.com/browserbase/sdk-python/blob/main/CONTRIBUTING.md Use the bootstrap script to automatically provision the Python environment and dependencies. ```sh $ ./scripts/bootstrap ``` -------------------------------- ### client.sessions.replays.retrieve_page Source: https://github.com/browserbase/sdk-python/blob/main/api.md Retrieves a specific page replay for a session. This method corresponds to the GET /v1/sessions/{id}/replays/{pageId} API endpoint. ```APIDOC ## GET /v1/sessions/{id}/replays/{pageId} ### Description Retrieves a specific page replay for a given session. ### Method GET ### Endpoint /v1/sessions/{id}/replays/{pageId} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the session. - **pageId** (string) - Required - The identifier of the specific page replay to retrieve. ``` -------------------------------- ### Get Session Debug Info Source: https://github.com/browserbase/sdk-python/blob/main/api.md Use the client.sessions.debug method to retrieve live URLs and debugging information for a specific session by its ID. ```python client.sessions.debug(id) ``` -------------------------------- ### Synchronous Client Constructor Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Instantiate the synchronous Browserbase client. You can override default settings like API key, base URL, timeout, and HTTP client. ```APIDOC ## Synchronous Client Constructor ### Description Instantiate the synchronous Browserbase client. You can override default settings like API key, base URL, timeout, and HTTP client. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters | Parameter | Type | Default | Description | |---|---|---|---| | api_key | str \| None | None | Override API key | | base_url | str \| httpx.URL \| None | None | Override base URL | | timeout | float \| Timeout \| None \| NotGiven | not_given | Override timeout | | http_client | httpx.Client \| None | None | Override HTTP client | | max_retries | int \| NotGiven | not_given | Override max retries | | default_headers | Mapping[str, str] \| None | None | Add to default headers | | set_default_headers | Mapping[str, str] \| None | None | Replace default headers | | default_query | Mapping[str, object] \| None | None | Add to default query | | set_default_query | Mapping[str, object] \| None | None | Replace default query | ### Example ```python client = Browserbase(api_key="key-1") # Per-request timeout override session = client.copy(timeout=5.0).sessions.create(project_id="proj-id") ``` ### `with_options()` Alias Alias for `copy()` for inline usage. ```python session = client.with_options(timeout=10).sessions.create(project_id="proj-id") ``` ### Context Manager ```python with Browserbase() as client: session = client.sessions.create(project_id="proj-id") ``` The client automatically closes HTTP connections when exiting the context manager. ``` -------------------------------- ### List Sessions (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md The v1 SDK provides a method to list sessions via `bb.sessions.list()`. ```python # v1 SDK sessions = bb.sessions.list() ``` -------------------------------- ### Get Project Usage Statistics Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/projects.md Retrieves usage statistics for a given project ID, including active sessions and data transfer. ```python usage = client.projects.usage("proj-123") print(f"Active sessions: {usage.sessions_active}") print(f"Sessions this month: {usage.sessions_this_month}") print(f"Proxy bytes: {usage.bytes_proxy}") ``` -------------------------------- ### Create a Context Source: https://github.com/browserbase/sdk-python/blob/main/api.md Use the client.contexts.create method to create a new context. Pass parameters as keyword arguments. ```python client.contexts.create(**params) ``` -------------------------------- ### Get Session Downloads (v0 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md This is the v0 SDK method for retrieving session downloads. The `retry_interval` parameter is no longer supported. ```python # v0 SDK downloads = browserbase.get_session_downloads(session_id=some_session.id) ``` -------------------------------- ### Configure Client Timeout Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/errors.md Shows how to set global, fine-grained, and per-request timeouts for the Browserbase client. ```python # Global timeout client = Browserbase(timeout=20.0) # Fine-grained control import httpx client = Browserbase( timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0) ) # Per-request client.with_options(timeout=5.0).sessions.create(project_id="proj") ``` -------------------------------- ### retrieve_page Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Gets the HLS playlist for a specific page within a session replay. This allows for streaming or saving the page content in HLS format. ```APIDOC ## retrieve_page ### Description Gets HLS playlist for a specific page. ### Method POST ### Endpoint /sessions/{id}/replays/pages/{page_id}/hls ### Parameters #### Path Parameters - **id** (str) - Required - Session ID - **page_id** (str) - Required - Page ID (from replay.pages[].page_id) ### Request Example ```json { "session_id": "session-id-123", "page_id": "page-id-456" } ``` ### Response #### Success Response (200) - **hls_playlist** (BinaryAPIResponse) - HLS .m3u8 playlist. ``` -------------------------------- ### Get Debug Connection URLs (v1 SDK) Source: https://github.com/browserbase/sdk-python/blob/main/MIGRATION.md The v1 SDK retrieves debug connection URLs using `bb.sessions.debug.list(id=...)`. ```python # v1 SDK debug_urls = bb.sessions.debug.list(id="some_session_id") ``` -------------------------------- ### Instantiate Synchronous Client Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/client.md Instantiate the synchronous Browserbase client with an API key. This client can be used to create sessions with per-request timeout overrides. ```python client = Browserbase(api_key="key-1") # Per-request timeout override session = client.copy(timeout=5.0).sessions.create(project_id="proj-id") ``` -------------------------------- ### Get Session Debugging URLs Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions.md Retrieve live debugging and inspection URLs for a specific session using its ID. The `debug` method returns a `SessionLiveURLs` object. ```python urls = client.sessions.debug("session-id-123") print(urls) ``` -------------------------------- ### Create Context SDK Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this snippet to create a new context. Requires a project ID. ```python context = client.contexts.create(project_id="proj-id") ``` -------------------------------- ### Enable SDK Logging Source: https://github.com/browserbase/sdk-python/blob/main/README.md Sets the BROWSERBASE_LOG environment variable to enable logging via the standard library. ```shell $ export BROWSERBASE_LOG=info ``` -------------------------------- ### Retrieve HLS Playlist for a Specific Page Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/sessions-subresources.md Gets the HLS playlist for a specific page within a session replay. This is used to stream or save page content for playback. ```python replay = client.sessions.replays.retrieve("session-id-123") page = replay.pages[0] # Get HLS playlist for first page hls_playlist = client.sessions.replays.retrieve_page( id="session-id-123", page_id=page.page_id ) ``` -------------------------------- ### Async Projects API Usage Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/api-reference/projects.md Demonstrates how to use the asynchronous versions of the Projects API methods with `AsyncBrowserbase`. ```python import asyncio from browserbase import AsyncBrowserbase async def main(): async with AsyncBrowserbase(api_key="key") as client: project = await client.projects.retrieve("proj-id") projects = await client.projects.list() usage = await client.projects.usage("proj-id") asyncio.run(main()) ``` -------------------------------- ### List All Projects Source: https://github.com/browserbase/sdk-python/blob/main/_autodocs/endpoints.md Use this method to retrieve a list of all projects associated with your account. ```python projects = client.projects.list() ```