### Install Browserbase TypeScript SDK Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx Instructions for installing the Browserbase TypeScript SDK using npm, pnpm, and yarn. ```bash npm install -S @browserbasehq/sdk ``` ```bash pnpm install -S @browserbasehq/sdk ``` ```bash yarn add @browserbasehq/sdk ``` -------------------------------- ### Install Browserbase Python SDK Source: https://github.com/browserbase/docs/blob/main/api-reference/python-sdk.mdx Install the Browserbase Python SDK using pip. This is the first step to integrating Browserbase into your Python projects. ```bash pip install browserbase ``` -------------------------------- ### Install Browserbase SDK for CrewAI Source: https://github.com/browserbase/docs/blob/main/integrations/crew-ai/python.mdx Installs the Browserbase SDK and the necessary CrewAI tools using pip. This is a prerequisite for integrating web browsing into your agent. ```bash pip install browserbase 'crewai[tools]' ``` -------------------------------- ### Install Browserbase SDK for Node.js Source: https://github.com/browserbase/docs/blob/main/integrations/langchain/javascript-typescript.mdx Installs the Browserbase SDK for Node.js using npm. This is a prerequisite for using Browserbase functionalities within your Node.js projects. ```bash npm i @browserbasehq/sdk ``` -------------------------------- ### Create Selenium Session with Python Source: https://github.com/browserbase/docs/blob/main/quickstart/selenium.mdx Establishes a Browserbase session and configures a Selenium WebDriver for connection. Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID. Returns the session ID and sets up the WebDriver to use it. Outputs the title of the navigated page. ```python from selenium import webdriver from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import requests import os def create_session(): url = 'https://www.browserbase.com/v1/sessions' headers = {'Content-Type': 'application/json', 'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]} response = requests.post(url, json={ "projectId": os.environ["BROWSERBASE_PROJECT_ID"] }, headers=headers) return response.json()['id'] class CustomRemoteConnection(RemoteConnection): _session_id = None def __init__(self, remote_server_addr: str, session_id: str): super().__init__(remote_server_addr) self._session_id = session_id def get_remote_connection_headers(self, parsed_url, keep_alive=False): headers = super().get_remote_connection_headers(parsed_url, keep_alive) headers.update({'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]}) headers.update({'session-id': self._session_id}) return headers def run(): session_id = create_session() custom_conn = CustomRemoteConnection('http://connect.browserbase.com/webdriver', session_id) options = webdriver.ChromeOptions() options.debugger_address = "localhost:9223" driver = webdriver.Remote(custom_conn, options=options) driver.get("https://www.browserbase.com") get_title = driver.title print(get_title) # Make sure to quit the driver so your session is ended! driver.quit() run() ``` -------------------------------- ### Install Browserbase Haystack Integration Package Source: https://github.com/browserbase/docs/blob/main/integrations/haystack/python.mdx Installs the 'browserbase-haystack' Python package using pip. This package provides the BrowserbaseFetcher component for integrating with the Haystack framework. ```bash pip install browserbase-haystack ``` -------------------------------- ### Create Selenium Session with TypeScript Source: https://github.com/browserbase/docs/blob/main/quickstart/selenium.mdx Initiates a new Browserbase session and configures a Selenium WebDriver instance to connect to it. Requires BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID environment variables. Outputs a WebDriver instance connected to a Browserbase session. ```typescript import http from "http"; import webdriver from "selenium-webdriver"; import chrome from "selenium-webdriver/chrome"; async function createSession() { const response = await fetch(`https://www.browserbase.com/v1/sessions`, { method: 'POST', headers: { "x-bb-api-key": process.env.BROWSERBASE_API_KEY, "Content-Type": "application/json" }, body: JSON.stringify({ projectId: process.env.BROWSERBASE_PROJECT_ID }) }); return await response.json(); } (async () => { const session = await createSession(); const customHttpAgent = new http.Agent({}); (customHttpAgent as any).addRequest = (req: any, options: any) => { // Session ID needs to be set here req.setHeader("session-id", session.id); req.setHeader("x-bb-api-key", process.env.BROWSERBASE_API_KEY); (http.Agent.prototype as any).addRequest.call(customHttpAgent, req, options); }; // We set a debuggerAddress so the server-side WebDriver can connect. const options = new chrome.Options(); options.debuggerAddress("localhost:9223"); const driver = new webdriver.Builder() .forBrowser("chrome") .setChromeOptions(options) .usingHttpAgent(customHttpAgent) .usingServer( `http://connect.browserbase.com/webdriver` // Selenium only supports HTTP ) .build(); await driver.get("https://www.browserbase.com"); // Make sure to quit the driver so your session is ended! await driver.quit(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### Start Session with Playwright (Python) Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Establishes a connection to BrowserBase using Playwright in Python. It utilizes `connect_over_cdp` to initiate the session and then accesses the first page for navigation. This code snippet requires the BROWSERBASE_API_KEY environment variable. ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): chromium = playwright.chromium browser = chromium.connect_over_cdp('wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}') context = browser.contexts[0] page = context.pages[0] with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### Python SDK: Capture Screenshots Source: https://context7.com/browserbase/docs/llms.txt Shows how to capture screenshots of webpages using the Browserbase Python SDK. This example includes capturing full-page screenshots and saving them to a file. Requires the browserbase Python package and an API key. ```python import os from browserbase import Browserbase browserbase = Browserbase(os.environ["BROWSERBASE_API_KEY"]) # Take full-page screenshot screenshot_bytes = browserbase.screenshot( "https://example.com", full_page=True ) # Save to file with open("screenshot.png", "wb") as f: f.write(screenshot_bytes); ``` -------------------------------- ### Connect to Browserbase with Selenium (Python) Source: https://github.com/browserbase/docs/blob/main/guides/browser-contexts-and-pages.mdx Shows how to integrate Browserbase with Selenium in Python. This example requires specific setup for RemoteConnection and session creation, as detailed in the Browserbase quickstart guide. It uses a debugger address to connect to the Browserbase session. ```python from selenium import webdriver from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import requests import os def run(): # see create_session and CustomRemoteConnection definition # at https://docs.browserbase.com/quickstart/selenium session_id = create_session() custom_conn = CustomRemoteConnection('http://connect.browserbase.com/webdriver', session_id) options = webdriver.ChromeOptions() options.debugger_address = "localhost:9223" driver = webdriver.Remote(custom_conn, options=options) driver.get("https://www.browserbase.com") # Selenium don't have the concept of BrowserContext and Pages get_title = driver.title print(get_title) # Make sure to quit the driver so your session is ended! driver.quit() run() ``` -------------------------------- ### Connect to Browserbase using Playwright in Python Source: https://github.com/browserbase/docs/blob/main/quickstart/playwright.mdx This Python code snippet illustrates how to connect to Browserbase using Playwright's sync_playwright and connect_over_cdp. It requires the BROWSERBASE_API_KEY environment variable. The code initializes Playwright, establishes a connection to Browserbase, accesses the default context and its page. ```python from playwright.sync_api import sync_playwright, Playwright import os def run(playwright: Playwright): chromium = playwright.chromium browser = chromium.connect_over_cdp('wss://connect.browserbase.com?apiKey='+ os.environ["BROWSERBASE_API_KEY"]) context = browser.contexts[0] page = context.pages[0] with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### TypeScript Custom HTTP Agent Source: https://github.com/browserbase/docs/blob/main/api-reference/connect.mdx Example of creating a custom HTTP agent in TypeScript to connect to Browserbase WebDriver, including session creation and header management. ```APIDOC ## POST /v1/sessions ### Description Creates a new Browserbase session to be used for WebDriver connections. ### Method POST ### Endpoint /v1/sessions ### Parameters #### Request Body - **projectId** (string) - Required - The ID of the project to create the session for. ### Request Example ```json { "projectId": "YOUR_PROJECT_ID" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created session. #### Response Example ```json { "id": "session_abc123" } ``` ## Using Custom HTTP Agent with Selenium WebDriver (TypeScript) ### Description This section demonstrates how to configure a custom HTTP agent in Selenium WebDriver for TypeScript to establish a connection with Browserbase WebDriver, including setting authentication headers. ### Method N/A (Configuration example) ### Endpoint `http://connect.browserbase.com/webdriver` ### Parameters #### Request Headers (for HTTP Agent) - **x-bb-api-key** (string) - Required - Your Browserbase API key for authentication. - **session-id** (string) - Required - The Session ID obtained from creating a session via the HTTP API. ### Request Example (Conceptual - Code Snippet) ```typescript import http from "http"; import webdriver from "selenium-webdriver"; import chrome from "selenium-webdriver/chrome"; async function createSession() { // ... (code to create session as shown above) } (async () => { const session = await createSession(); const customHttpAgent = new http.Agent({}); (customHttpAgent as any).addRequest = (req: any, options: any) => { req.setHeader("session-id", session.id); req.setHeader("x-bb-api-key", process.env.BROWSERBASE_API_KEY); (http.Agent.prototype as any).addRequest.call( customHttpAgent, req, options, ); }; const options = new chrome.Options(); options.debuggerAddress("localhost:9223"); const driver = new webdriver.Builder() .forBrowser("chrome") .setChromeOptions(options) .usingHttpAgent(customHttpAgent) .usingServer( `http://connect.browserbase.com/webdriver`, ) .build(); await driver.get("https://www.browserbase.com"); await driver.quit(); })().catch((error) => console.error(error.message)); ``` ### Response N/A (Configuration example) ``` -------------------------------- ### GET /v1/sessions Source: https://context7.com/browserbase/docs/llms.txt Retrieve all browser sessions for your project to monitor activity and usage. This endpoint provides a list of all sessions associated with your API key. ```APIDOC ## GET /v1/sessions ### Description Retrieve all browser sessions for your project to monitor activity and usage. This endpoint provides a list of all sessions associated with your API key. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions ### Parameters #### Headers - **x-bb-api-key** (string) - Required - Your Browserbase API key. ### Request Example ```bash curl -X GET https://www.browserbase.com/v1/sessions \ -H "x-bb-api-key: YOUR_API_KEY" ``` ### Response #### Success Response (200 OK) - An array of session objects, each containing: - **id** (string) - The unique identifier for the session. - **createdAt** (string) - Timestamp when the session was created. - **startedAt** (string|null) - Timestamp when the session started execution. - **endedAt** (string|null) - Timestamp when the session ended execution. - **projectId** (string) - The ID of the project this session belongs to. - **status** (string) - The current status of the session. - **proxyBytes** (integer) - Amount of data transferred via proxy in bytes. - **avg_cpu_usage** (number) - Average CPU usage of the session. - **memory_usage** (integer) - Memory usage of the session in bytes. #### Response Example ```json [ { "id": "1b4d49fc-f018-40e6-9287-df7bc19e351d", "createdAt": "2025-11-14T10:00:00.000Z", "startedAt": "2025-11-14T10:00:05.000Z", "endedAt": "2025-11-14T10:15:30.000Z", "projectId": "a3c8f9e2-d017-30e5-8176-ce6ab18d340c", "status": "COMPLETED", "proxyBytes": 2048576, "avg_cpu_usage": 45.2, "memory_usage": 512000000 } ] ``` ``` -------------------------------- ### Start Session with Puppeteer (TypeScript) Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Initiates a session using Puppeteer in TypeScript. It connects to BrowserBase via a WebSocket endpoint, creates a new page, navigates, and then closes the page and browser. Requires the BROWSERBASE_API_KEY environment variable. ```typescript import puppeteer from "puppeteer-core"; (async () => { const browser = await puppeteer.connect({ browserWSEndpoint: `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}`, }); const page = await browser.newPage(); await page.goto("https://www.browserbase.com"); await page.close(); await browser.close(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### Connect to Browserbase using Puppeteer Core Source: https://github.com/browserbase/docs/blob/main/quickstart/puppeteer.mdx This TypeScript code snippet shows how to connect to Browserbase using the puppeteer-core library. It requires your Browserbase API key and establishes a WebSocket endpoint for browser control. The snippet connects to Browserbase, opens a new page, navigates to a URL, and then closes the page and browser. ```typescript import puppeteer from "puppeteer-core"; (async () => { const browser = await puppeteer.connect({ browserWSEndpoint: `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}` }); const page = await browser.newPage(); await page.goto("https://www.browserbase.com"); await page.close(); await browser.close(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### Start Session with Playwright (TypeScript) Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Connects to BrowserBase using Playwright in TypeScript. It establishes a CDP connection, opens a page, navigates to a URL, and then closes the page and browser. Assumes BROWSERBASE_API_KEY environment variable is set. ```typescript import { chromium } from "playwright-core"; (async () => { const browser = await chromium.connectOverCDP( `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}`, ); const defaultContext = browser.contexts()[0]; const page = defaultContext.pages()[0]; await page.goto("https://www.browserbase.com"); await page.close(); await browser.close(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### List Browserbase Sessions (TypeScript) Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx Demonstrates how to retrieve a list of all available Browserbase sessions using the TypeScript SDK. The returned data structure matches the response type of the `GET /v1/sessions` API endpoint. ```typescript import { Browserbase } from "@browserbasehq/sdk"; const browserbase = new Browserbase(); const sessions = await browserbase.listSessions(); ``` -------------------------------- ### Download Files using Puppeteer (TypeScript) Source: https://github.com/browserbase/docs/blob/main/features/screenshots-and-downloads.mdx This example demonstrates how to set up Puppeteer to handle file downloads. It uses the CDP client to configure the download path and includes a function to fetch and save downloaded files. Dependencies include 'puppeteer-core' and 'node:fs'. ```typescript import puppeteer from "puppeteer-core"; import { writeFileSync } from "node:fs"; async function saveDownloadsOnDisk(sessionId: string, retryForSeconds: number) { return new Promise((resolve, reject) => { let pooler; const timeout = setTimeout(() => { if (pooler) { clearInterval(pooler); } }, retryForSeconds); async function fetchDownloads() { try { const response = await fetch( `https://www.browserbase.com/v1/sessions/${sessionId}/downloads`, { method: "GET", headers: { "x-bb-api-key": process.env.BROWSERBASE_API_KEY!, }, }, ); const arrayBuffer = await response.arrayBuffer(); if (arrayBuffer.byteLength > 0) { const buffer = Buffer.from(arrayBuffer); writeFileSync("downloads.zip", buffer); clearInterval(pooler); clearTimeout(timeout); resolve(); } } catch (e) { clearInterval(pooler); clearTimeout(timeout); reject(e); } } pooler = setInterval(fetchDownloads, 2000); }); } (async () => { // `createSession()` performs a call to the Browserbase Session API const { id: sessionId } = await createSession(); const browser = await puppeteer.connect({ // we connect to a Session created via the API browserWSEndpoint: `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}&sessionId=${sessionId}`, }); const page = await browser.newPage(); const client = await page.createCDPSession(); await client.send("Page.setDownloadBehavior", { behavior: "allow", downloadPath: "downloads", //@ts-ignore eventsEnabled: true, }); await page.goto("https://www.browserbase.com"); await page.close(); await browser.close(); // wait up to 20s to save the downloaded files locally ``` -------------------------------- ### Connect to Browserbase using Playwright in TypeScript Source: https://github.com/browserbase/docs/blob/main/quickstart/playwright.mdx This TypeScript code snippet shows how to connect to Browserbase using Playwright's chromium.connectOverCDP function. It requires the BROWSERBASE_API_KEY environment variable. The snippet establishes a connection, accesses the default context and page, navigates to a URL, and then closes the page and browser. ```typescript import { chromium } from "playwright-core"; (async () => { const browser = await chromium.connectOverCDP( `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}` ); //Getting the default context to ensure the sessions are recorded. const defaultContext = browser.contexts()[0]; const page = defaultContext.pages()[0]; await page.goto("https://browserbase.com/"); await page.close(); await browser.close(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### Access First Page and BrowserContext with Playwright (Python) Source: https://github.com/browserbase/docs/blob/main/guides/browser-contexts-and-pages.mdx Provides a Python example using Playwright to connect to Browserbase and retrieve the initial BrowserContext and Page. This code requires the playwright Python package and the BROWSERBASE_API_KEY environment variable. ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): chromium = playwright.chromium browser = chromium.connect_over_cdp('wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}') # Make sure to grab the first BrowserContext and Page context = browser.contexts[0] page = context.pages[0] # Act on Page # ... with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### Retrieve and Save Session Downloads with SDK Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx This example illustrates how to retrieve and save session downloads to a local file using the Browserbase SDK. It includes session creation, connecting to the browser via Playwright, and then using `getSessionDownloads` with retry parameters to ensure file availability. ```typescript import { Browserbase } from "@browserbasehq/sdk"; import { chromium } from "playwright-core"; (async () => { const browserbase = new Browserbase(); const { id: sessionId } = await browserbase.createSession(); const browser = await chromium.connectOverCDP( browserbase.connectUrl({ sessionId }), ); // ...navigate the page and take actions... await browserbase.getSessionDownloads(sessionId, "downloads.zip"); })(); ``` -------------------------------- ### Authenticate Browserbase API Requests Source: https://github.com/browserbase/docs/blob/main/api-reference/apis.mdx Demonstrates how to authenticate API requests to Browserbase using an API Key. This is essential for all REST endpoint interactions. Ensure your API key is securely stored and accessed, for example, via environment variables. ```TypeScript const response = await fetch( `https://www.browserbase.com/v1/sessions/${sessionId}`, { method: "GET", headers: { "x-bb-api-key": `${process.env.BROWSERBASE_API_KEY}`, }, }, ); ``` ```Python import requests import os url = "https://www.browserbase.com/v1/sessions" headers = {"x-bb-api-key": os.environ["BROWSERBASE_API_KEY"]} response = requests.request("GET", url, headers=headers) ``` ```cURL curl -X GET "https://www.browserbase.com/v1/sessions/${SESSION_ID}" \ -H "x-bb-api-key: ${BROWSERBASE_API_KEY}" \ ``` -------------------------------- ### Enable Proxies with Playwright (Python) Source: https://github.com/browserbase/docs/blob/main/features/stealth-mode.mdx Connects to Browserbase using Playwright for Python and enables proxy by setting `enableProxy=true` in the connection string. This example demonstrates initiating a connection, accessing the default context and page, and navigating to a URL. Ensure the BROWSERBASE_API_KEY environment variable is set. ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): chromium = playwright.chromium browser = chromium.connect_over_cdp('wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}&enableProxy=true') context = browser.contexts[0] page = context.pages[0] with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### Enable Proxies with Puppeteer (TypeScript) Source: https://github.com/browserbase/docs/blob/main/features/stealth-mode.mdx Connects to Browserbase using Puppeteer Core and enables proxy by setting `enableProxy=true`. This example shows how to establish a connection, open a new page, navigate to a URL, and then close the browser and page. Ensure the BROWSERBASE_API_KEY environment variable is set. ```typescript import puppeteer from "puppeteer-core"; (async () => { const browser = await puppeteer.connect({ browserWSEndpoint: `wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}&enableProxy=true`, }); const page = await browser.newPage(); await page.goto("https://www.browserbase.com"); await page.close(); await browser.close(); })().catch((error) => console.error(error.message)); ``` -------------------------------- ### Get Browserbase Connect URL (TypeScript) Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx Provides an example of generating a Connect API URL using the Browserbase TypeScript SDK. This URL is used to connect Puppeteer or Playwright to Browserbase, with support for session IDs and proxying. ```typescript import { Browserbase } from "@browserbasehq/sdk"; import { chromium } from "playwright-core"; (async () => { const browserbase = new Browserbase(); const browser = await chromium.connectOverCDP(browserbase.connectUrl()); // ... })(); ``` -------------------------------- ### Python SDK: Initialize and Load Pages Source: https://context7.com/browserbase/docs/llms.txt Demonstrates initializing the Browserbase Python SDK and loading web page content. It shows how to load single or multiple URLs, extract HTML, and retrieve only text content. Requires the browserbase Python package and an API key. ```python import os from browserbase import Browserbase # Initialize client browserbase = Browserbase(os.environ["BROWSERBASE_API_KEY"]) # Load single page as HTML html_content = browserbase.load("https://example.com") # Load multiple pages urls = ["https://example.com", "https://example.org"] results = browserbase.load(urls) for html in results: print(f"Content length: {len(html)}") # Extract text only text_content = browserbase.load( "https://example.com", text_content=True ); ``` -------------------------------- ### Browserbase SDK - Initialize Client Source: https://context7.com/browserbase/docs/llms.txt Create a Browserbase SDK client for simplified browser operations in TypeScript applications. ```APIDOC ## TypeScript SDK - Initialize Client ### Description Create a Browserbase SDK client for simplified browser operations in TypeScript applications. ### Usage ```typescript import { Browserbase } from "@browserbasehq/sdk"; const browserbase = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY, projectId: process.env.BROWSERBASE_PROJECT_ID }); // Create a session with custom fingerprint const { id: sessionId } = await browserbase.createSession({ fingerprint: { devices: ["mobile"], locales: ["en-US"] } }); console.log(`Session created: ${sessionId}`); ``` ``` -------------------------------- ### Initialize Browserbase Client (TypeScript) Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx Demonstrates how to initialize a Browserbase client instance in TypeScript. The SDK can be initialized with optional configuration parameters. If not provided, it attempts to load API keys from environment variables. ```typescript import { Browserbase } from "@browserbasehq/sdk"; // Init the SDK const browserbase = new Browserbase(); ``` -------------------------------- ### GET /v1/sessions/SESSION_ID Source: https://context7.com/browserbase/docs/llms.txt Get detailed information about a specific browser session including status, resource usage, and timing data. This endpoint is useful for tracking the progress and outcome of individual sessions. ```APIDOC ## GET /v1/sessions/SESSION_ID ### Description Get detailed information about a specific browser session including status, resource usage, and timing data. This endpoint is useful for tracking the progress and outcome of individual sessions. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions/SESSION_ID ### Parameters #### Path Parameters - **SESSION_ID** (string) - Required - The unique identifier of the session to retrieve. #### Headers - **x-bb-api-key** (string) - Required - Your Browserbase API key. ### Request Example ```bash curl -X GET https://www.browserbase.com/v1/sessions/SESSION_ID \ -H "x-bb-api-key: YOUR_API_KEY" ``` ### Response #### Success Response (200 OK) - **id** (string) - The unique identifier for the session. - **createdAt** (string) - Timestamp when the session was created. - **startedAt** (string|null) - Timestamp when the session started execution. - **endedAt** (string|null) - Timestamp when the session ended execution. - **projectId** (string) - The ID of the project this session belongs to. - **status** (string) - The current status of the session. - **taskId** (string) - Identifier for the task associated with the session. - **proxyBytes** (integer) - Amount of data transferred via proxy in bytes. - **expiresAt** (string) - Timestamp when the session data will expire. - **avg_cpu_usage** (number) - Average CPU usage of the session. - **memory_usage** (integer) - Memory usage of the session in bytes. #### Response Example ```json { "id": "1b4d49fc-f018-40e6-9287-df7bc19e351d", "createdAt": "2025-11-14T10:00:00.000Z", "startedAt": "2025-11-14T10:00:05.000Z", "endedAt": "2025-11-14T10:15:30.000Z", "projectId": "a3c8f9e2-d017-30e5-8176-ce6ab18d340c", "status": "COMPLETED", "taskId": "5f8g10h3-e128-41g6-9287-fg7cd29f573g", "proxyBytes": 2048576, "expiresAt": "2025-11-14T11:00:00.000Z", "avg_cpu_usage": 45.2, "memory_usage": 512000000 } ``` ``` -------------------------------- ### Initialize Browserbase Client Source: https://github.com/browserbase/docs/blob/main/api-reference/python-sdk.mdx Initialize the Browserbase client in Python. Requires your API key, which can be provided directly or loaded from an environment variable. ```python from browserbase import Browserbase # Init the SDK browserbase = Browserbase(os.environ["BROWSERBASE_API_KEY"]) ``` -------------------------------- ### GET /sessions/{SESSION_ID}/downloads Source: https://context7.com/browserbase/docs/llms.txt Download all files that were downloaded during the browser session as a ZIP archive. ```APIDOC ## GET /sessions/{SESSION_ID}/downloads ### Description Download all files that were downloaded during the browser session as a ZIP archive. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions/SESSION_ID/downloads ### Parameters #### Header Parameters - **x-bb-api-key** (string) - Required - Your Browserbase API key. #### Path Parameters - **SESSION_ID** (string) - Required - The unique identifier for the session. ### Response #### Success Response (200) - **ZIP archive** - A compressed archive containing all downloaded files from the session. ``` -------------------------------- ### GET /sessions/{SESSION_ID}/recording Source: https://context7.com/browserbase/docs/llms.txt Download Chrome DevTools Protocol recording data for session replay and analysis. ```APIDOC ## GET /sessions/{SESSION_ID}/recording ### Description Download Chrome DevTools Protocol recording data for session replay and analysis. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions/SESSION_ID/recording ### Parameters #### Header Parameters - **x-bb-api-key** (string) - Required - Your Browserbase API key. #### Path Parameters - **SESSION_ID** (string) - Required - The unique identifier for the session. ### Response #### Success Response (200) - **Array of recording event objects** - Contains events related to the session recording, such as frame navigation. #### Response Example ```json [ { "type": "Page.frameNavigated", "time": "1713541653", "data": { "frame": { "id": "frame-123", "url": "https://browserbase.com/" } } } ] ``` ``` -------------------------------- ### GET /sessions/{SESSION_ID}/debug Source: https://context7.com/browserbase/docs/llms.txt Retrieve URLs for real-time remote access to a running browser session for live debugging. ```APIDOC ## GET /sessions/{SESSION_ID}/debug ### Description Retrieve URLs for real-time remote access to a running browser session for live debugging. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions/SESSION_ID/debug ### Parameters #### Header Parameters - **x-bb-api-key** (string) - Required - Your Browserbase API key. #### Path Parameters - **SESSION_ID** (string) - Required - The unique identifier for the session. ### Response #### Success Response (200) - **Debug URLs object** - Contains URLs for fullscreen debugging, standard debugging, and WebSocket connection. #### Response Example ```json { "debuggerFullscreenUrl": "https://debug.browserbase.com/fullscreen/SESSION_ID", "debuggerUrl": "https://debug.browserbase.com/SESSION_ID", "wsUrl": "wss://connect.browserbase.com/debug/SESSION_ID" } ``` ``` -------------------------------- ### GET /sessions/{SESSION_ID}/logs Source: https://context7.com/browserbase/docs/llms.txt Retrieve detailed Chrome DevTools Protocol logs for debugging and analyzing browser session behavior. ```APIDOC ## GET /sessions/{SESSION_ID}/logs ### Description Access detailed Chrome DevTools Protocol logs for debugging and analyzing browser session behavior. ### Method GET ### Endpoint https://www.browserbase.com/v1/sessions/SESSION_ID/logs ### Parameters #### Header Parameters - **x-bb-api-key** (string) - Required - Your Browserbase API key. #### Path Parameters - **SESSION_ID** (string) - Required - The unique identifier for the session. ### Response #### Success Response (200) - **Array of log objects** - Contains log entries with details like id, sessionId, timestamp, method, request, and response information. #### Response Example ```json [ { "id": "log-123", "sessionId": "1b4d49fc-f018-40e6-9287-df7bc19e351d", "timestamp": "1713541653", "method": "Network.requestWillBeSent", "request": { "timestamp": "1713541653", "params": { "requestId": "req-456", "request": { "url": "https://browserbase.com/", "method": "GET" } } }, "response": { "timestamp": "1713541654", "result": { "status": 200 } } } ] ``` ``` -------------------------------- ### Initialize Browserbase Client with TypeScript SDK Source: https://context7.com/browserbase/docs/llms.txt Initializes the Browserbase SDK client in a TypeScript application, enabling interaction with the Browserbase API. Requires API and Project IDs, typically set via environment variables. ```typescript import { Browserbase } from "@browserbasehq/sdk"; const browserbase = new Browserbase({ apiKey: process.env.BROWSERBASE_API_KEY, projectId: process.env.BROWSERBASE_PROJECT_ID }); // Create a session with custom fingerprint const { id: sessionId } = await browserbase.createSession({ fingerprint: { devices: ["mobile"], locales: ["en-US"] } }); console.log(`Session created: ${sessionId}`); ``` -------------------------------- ### Load Images with Browserbase and GPT-4 Vision in Langchain Source: https://github.com/browserbase/docs/blob/main/integrations/langchain/python.mdx Takes a screenshot of a webpage using Browserbase and processes it with GPT-4 Vision for image analysis. Requires Browserbase and Langchain OpenAI SDKs. Outputs the analysis result. ```python from browserbase import Browserbase from browserbase.helpers.gpt4 import GPT4VImage, GPT4VImageDetail from langchain_core.messages import HumanMessage from langchain_openai import ChatOpenAI chat = ChatOpenAI(model="gpt-4-vision-preview", max_tokens=256) browser = Browserbase() screenshot = browser.screenshot("https://browserbase.com") result = chat.invoke( [ HumanMessage( content=[ {"type": "text", "text": "What color is the logo?"}, GPT4VImage(screenshot, GPT4VImageDetail.auto), ] ) ] ) print(result.content) ``` -------------------------------- ### GET /v1/sessions/[sessionid]/downloads Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Retrieve downloaded files from a completed session. This endpoint allows access to any files that were downloaded during the session. ```APIDOC ## GET /v1/sessions/[sessionid]/downloads ### Description Retrieve downloaded files from a completed session. This endpoint allows access to any files that were downloaded during the session. ### Method GET ### Endpoint /v1/sessions/[sessionid]/downloads ### Parameters #### Path Parameters - **sessionid** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **files** (array) - A list of objects, where each object contains information about a downloaded file, such as its name and download URL. #### Response Example ```json { "files": [ { "name": "document.pdf", "download_url": "https://example.com/downloads/session_abc123/document.pdf" }, { "name": "image.png", "download_url": "https://example.com/downloads/session_abc123/image.png" } ] } ``` ``` -------------------------------- ### GET /v1/sessions/[sessionid]/recording Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Access the recording of a completed session. This endpoint provides access to the video recording of the browser session. ```APIDOC ## GET /v1/sessions/[sessionid]/recording ### Description Access the recording of a completed session. This endpoint provides access to the video recording of the browser session. ### Method GET ### Endpoint /v1/sessions/[sessionid]/recording ### Parameters #### Path Parameters - **sessionid** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **recording_url** (string) - A URL to access the session recording. #### Response Example ```json { "recording_url": "https://example.com/recordings/session_abc123.mp4" } ``` ``` -------------------------------- ### GET /v1/sessions/[sessionid]/logs Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Access logs for a completed session. This endpoint allows retrieval of all logs associated with a specific session ID. ```APIDOC ## GET /v1/sessions/[sessionid]/logs ### Description Access logs for a completed session. This endpoint allows retrieval of all logs associated with a specific session ID. ### Method GET ### Endpoint /v1/sessions/[sessionid]/logs ### Parameters #### Path Parameters - **sessionid** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **logs** (array) - An array of log objects, each containing details like timestamp and message. #### Response Example ```json { "logs": [ { "timestamp": "2023-10-27T10:00:00Z", "message": "Session started." }, { "timestamp": "2023-10-27T10:05:15Z", "message": "Page loaded successfully." } ] } ``` ``` -------------------------------- ### client.createSession Source: https://github.com/browserbase/docs/blob/main/api-reference/typescript-sdk.mdx Creates a new browser session with optional configuration. ```APIDOC ## POST /v1/sessions ### Description Creates a new browser session. You can optionally specify a project ID, extension ID, and fingerprint options. ### Method POST ### Endpoint /v1/sessions ### Parameters #### Request Body - **options** (object) - Optional. Configuration for the new session. - **projectId** (string) - Optional. A valid Project ID. - **extensionId** (string) - Optional. A valid Extension ID. - **fingerprint** (object) - Optional. Fingerprint options for the session (e.g., `devices: ["mobile"]`). ### Request Example ```json { "fingerprint": { "devices": ["mobile"] } } ``` ### Response #### Success Response (201 Created) - **id** (string) - The unique ID of the newly created session. #### Response Example ```json { "id": "session_abc123" } ``` ``` -------------------------------- ### GET /v1/sessions/[sessionid]/debug Source: https://github.com/browserbase/docs/blob/main/features/sessions.mdx Access debug connection information for a completed session. This endpoint provides details useful for debugging the connection to the session. ```APIDOC ## GET /v1/sessions/[sessionid]/debug ### Description Access debug connection information for a completed session. This endpoint provides details useful for debugging the connection to the session. ### Method GET ### Endpoint /v1/sessions/[sessionid]/debug ### Parameters #### Path Parameters - **sessionid** (string) - Required - The unique identifier of the session. ### Response #### Success Response (200) - **debug_info** (object) - An object containing debug connection details, such as IP addresses, ports, and protocols. #### Response Example ```json { "debug_info": { "ip_address": "192.168.1.100", "port": 9222, "protocol": "ws" } } ``` ``` -------------------------------- ### Python: Create and Connect to Browserbase Session Source: https://context7.com/browserbase/docs/llms.txt This Python snippet demonstrates how to create a Browserbase session, establish a custom remote connection, configure Chrome options for debugging, and initialize a WebDriver instance. It then navigates to a webpage, retrieves its title, and prints it. Finally, it quits the session. ```python from browserbase import BrowserbaseClient from selenium import webdriver # Assuming you have a way to get a session_id, e.g., from an API call or environment variable session_id = "YOUR_SESSION_ID" # Custom connection for Browserbase HTTP endpoint class CustomRemoteConnection(webdriver.Remote.RemoteConnection): def __init__(self, remote_server_addr, session_id): self.remote_server_addr = remote_server_addr self.session_id = session_id self.command_executor = remote_server_addr def getCommandExecutor(self): return self.command_executor def getSessionID(self): return self.session_id custom_conn = CustomRemoteConnection( 'http://connect.browserbase.com/webdriver', session_id ) options = webdriver.ChromeOptions() # Example: options.debugger_address = "localhost:9223" driver = webdriver.Remote(custom_conn, options=options) driver.get("https://www.browserbase.com") title = driver.title print(f"Page title: {title}") # Important: quit to end session and stop billing driver.quit() ``` -------------------------------- ### Get Debug Connection URLs using cURL Source: https://context7.com/browserbase/docs/llms.txt Retrieves URLs for real-time remote debugging access to a running browser session. Requires a session ID and API key. ```bash curl -X GET https://www.browserbase.com/v1/sessions/SESSION_ID/debug \ -H "x-bb-api-key: YOUR_API_KEY" ``` -------------------------------- ### Create Session with Fingerprinting (Playwright/Selenium Python) Source: https://github.com/browserbase/docs/blob/main/features/stealth-mode.mdx Shows how to initiate a Browserbase session with specified fingerprinting configurations (locales, operating systems) using Playwright and Selenium in Python. Includes steps for connecting and interacting with a web page. ```python from playwright.sync_api import sync_playwright import requests import os def create_session(): url = 'https://www.browserbase.com/v1/sessions' headers = {'Content-Type': 'application/json', 'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]} json = { "projectId": os.environ["BROWSERBASE_PROJECT_ID"], # Fingerprint options "fingerprint": { "locales": ["en", "en-US", "de"], "operatingSystems": ["android"] } } response = requests.post(url, json=json, headers=headers) return response.json()['id'] def run(): with sync_playwright() as p: session_id = create_session() browser = await p.chromium.connect_over_cdp( f"wss://connect.browserbase.com?apiKey={os.environ['BROWSERBASE_API_KEY']}&sessionId={session_id}" ) context = await browser.new_context() page = await context.new_page() await page.goto("https://www.browserbase.com") await page.close() await context.close() await browser.close() run() ``` ```python from selenium import webdriver from selenium.webdriver.remote.remote_connection import RemoteConnection from selenium.webdriver.common.desired_capabilities import DesiredCapabilities import requests import os def create_session(): url = 'https://www.browserbase.com/v1/sessions' headers = {'Content-Type': 'application/json', 'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]} json = { "projectId": os.environ["BROWSERBASE_PROJECT_ID"], # Fingerprint options "fingerprint": { "locales": ["en", "en-US", "de"], "operatingSystems": ["android"] } } response = requests.post(url, json=json, headers=headers) return response.json()['id'] class CustomRemoteConnection(RemoteConnection): _session_id = None def __init__(self, remote_server_addr: str, session_id: str): super().__init__(remote_server_addr) self._session_id = session_id def get_remote_connection_headers(self, parsed_url, keep_alive=False): headers = super().get_remote_connection_headers(parsed_url, keep_alive) headers.update({'x-bb-api-key': os.environ["BROWSERBASE_API_KEY"]}) headers.update({'session-id': self._session_id}) # enable proxy here headers.update({'enable-proxy': "true"}) return headers def run(): session_id = create_session() custom_conn = CustomRemoteConnection('http://connect.browserbase.com/webdriver', session_id) options = webdriver.ChromeOptions() options.debugger_address = "localhost:9223" ``` -------------------------------- ### GET /v1/sessions/{sessionId}/debug Source: https://github.com/browserbase/docs/blob/main/guides/session-debug-connection/integrate-live-session.mdx Retrieves the debug connection URL for a specific session. This URL can be used to embed a live view of the automation session in an iframe. ```APIDOC ## GET /v1/sessions/{sessionId}/debug ### Description Retrieves the debug connection URL for a specific session. This URL can be used to embed a live view of the automation session in an iframe. ### Method GET ### Endpoint /v1/sessions/{sessionId}/debug ### Parameters #### Path Parameters - **sessionId** (string) - Required - The ID of the session for which to retrieve the debug URL. ### Response #### Success Response (200) - **debuggerFullscreenUrl** (string) - The URL for the live debug view of the session. #### Response Example ```json { "debuggerFullscreenUrl": "https://debug.browserbase.com/session_id_12345" } ``` ```