ScreenshotNeo

BlogHow-to

LambdaTest Screenshot API Examples in Python for Capturing Web Pages

Submit a screenshot job to the LambdaTest API with Python, retrieve its results by test ID, and inspect each screenshot record before using it.

By the ScreenshotNeo team4 October 20269 min read

To capture a web page with the LambdaTest Screenshot API, send a JSON POST request to https://api.lambdatest.com/screenshots/v1/ using HTTP Basic authentication. Save the returned test_id, then send an authenticated GET request to the same endpoint with that ID and inspect the test status and screenshot records before using their URLs.

The current support and API pages use the name TestMu AI (formerly LambdaTest); the documented API host remains api.lambdatest.com. TestMu AI describes its Automated Screenshot API as capturing full-page screenshots of URLs through an API call to its cloud servers. See the start-test API reference and the Automated Screenshot API support guide.

What the workflow does

  1. Put your account username and access key in environment variables or a secret store.
  2. Choose the URL and browser/OS configurations for the test matrix.
  3. POST the JSON payload with Basic authentication.
  4. Keep the returned test_id.
  5. GET the result using that ID; inspect test and per-screenshot statuses.
  6. Use screenshot URLs only for records that are ready and successful.

This is a hosted screenshot test workflow. It is different from taking a screenshot with a locally installed browser through Selenium: the API submits a job to the service, which returns test details and screenshot records.

Configure credentials safely

Set the credentials in your shell before running the example. The API reference documents Basic authentication as an Authorization header containing Basic followed by the Base64-encoded username:password. Python Requests can create that header from an auth=(username, password) tuple.

export LT_USERNAME="your_username"
export LT_ACCESS_KEY="your_access_key"

For CI, use the platform’s secret-variable facility. Do not commit credentials, print them in logs, put them in a URL, or include them in an exception message. Rotate a key if it has been exposed.

Runnable Python example

Install the dependency with python -m pip install requests. The example submits one configuration, checks HTTP errors, retains the ID, retrieves the result, and prints screenshot metadata. It uses ordinary Requests Basic authentication as an example pattern; it is not a claim that a vendor SDK was used or tested.

import os
import sys
import requests

START_URL = "https://api.lambdatest.com/screenshots/v1/"

username = os.environ.get("LT_USERNAME")
access_key = os.environ.get("LT_ACCESS_KEY")
if not username or not access_key:
    sys.exit("Set LT_USERNAME and LT_ACCESS_KEY before running this script.")

# Select a URL and configurations supported by your account.
payload = {
    "url": "https://example.com",
    "configs": [
        {
            " os": "Windows 10",
            "browser": "Chrome",
            "resolution": "1366x768"
        }
    ]
}

with requests.Session() as session:
    session.auth = (username, access_key)
    session.headers.update({"Accept": "application/json"})

    start_response = session.post(START_URL, json=payload, timeout=60)
    start_response.raise_for_status()
    start_data = start_response.json()

    test_id = start_data.get("test_id")
    if not test_id:
        raise RuntimeError(f"Start response did not contain test_id: {start_data}")
    print("Submitted test:", test_id)

    result_url = f"{START_URL}{test_id}"
    result_response = session.get(result_url, timeout=60)
    result_response.raise_for_status()
    result_data = result_response.json()

    print("Test status:", result_data.get("status"))
    screenshots = result_data.get("screenshots", [])
    for item in screenshots:
        print({
            "os": item.get("os"),
            "browser": item.get("browser"),
            "browser_version": item.get("browser_version"),
            "status": item.get("status"),
            "resolution": item.get("resolution"),
            "screenshot_url": item.get("screenshot_url"),
            "thumbnail_url": item.get("thumbnail_url"),
            "activity_id": item.get("activity_id"),
        })

Check the configuration field names and values against the current API reference before using this payload. The reference lists fields including url, defer_time, email, mac_res, win_res, tunnel, tunnel_identifier, username, password, callback_url, and configs. The example uses only url and configs; the service may require or accept other fields depending on the desired setup. The API reference is authoritative for required fields and currently supported values.

In the code, change url to the page you own or are authorized to capture. Set the OS, browser, browser version and resolution in the format currently accepted by the API. The shown values illustrate the payload shape; they are not a promise that a particular historical browser version or platform is currently available.

Choosing a useful browser and resolution matrix

A configuration represents an environment in which the page is captured. Choose the dimensions based on the question you need the screenshots to answer:

Dimension What it changes How to choose
Operating system The platform rendering the page Include the operating systems relevant to your users or release support.
Browser and version The browser engine and its version Use versions available in the current service catalog; verify availability rather than copying an old example.
Resolution The viewport/image dimensions used for the capture Pick representative desktop or other target sizes for the layouts you need to inspect.

Start with a small matrix that covers the environments tied to a real requirement. Add configurations when you need to diagnose a rendering difference or validate another supported environment. More configurations mean more result records to review and can affect your account’s usage or plan limits; consult the service’s current account and API documentation for those limits. The available source material does not establish a complete current platform catalog or pricing comparison.

Retrieve results and interpret the response

The start response contains a test_id. The result request is a GET to the screenshot endpoint followed by that ID, authenticated with the same account credentials. Its response includes a test status and screenshot records. A record can include operating system, browser, browser version, status, screenshot URL, thumbnail URL, activity ID and resolution. See the API reference and support guide.

Do not treat the presence of a record or URL as proof that the capture succeeded. Check the overall test status and each record’s status, then use the screenshot URL for a successful, usable capture. Preserve the test ID with your logs or job record so you can query the result again and correlate a failure with its environment. Avoid logging sensitive page URLs if they contain tokens or private data.

The example makes one result request. The documentation cited here does not establish a fixed completion time, required polling interval, or retry schedule. If the response indicates that work is still in progress, follow the current service guidance for checking again; do not assume an arbitrary sleep guarantees completion. For unattended workflows, store the test ID durably and make result retrieval restartable.

Equivalent request examples

These examples use the same two-step flow. Keep the credentials in environment variables. They use basic HTTP request patterns; check the current API reference for payload requirements and supported configuration names.

cURL

export LT_USERNAME="your_username"
export LT_ACCESS_KEY="your_access_key"

curl --fail-with-body --user "$LT_USERNAME:$LT_ACCESS_KEY" \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"url":"https://example.com","configs":[{"os":"Windows 10","browser":"Chrome","resolution":"1366x768"}]}' \
  'https://api.lambdatest.com/screenshots/v1/'

Read test_id from the JSON response, then retrieve the result:

curl --fail-with-body --user "$LT_USERNAME:$LT_ACCESS_KEY" \
  --header 'Accept: application/json' \
  'https://api.lambdatest.com/screenshots/v1/TEST_ID'

Node.js

const username = process.env.LT_USERNAME;
const accessKey = process.env.LT_ACCESS_KEY;
if (!username || !accessKey) throw new Error('Set LT_USERNAME and LT_ACCESS_KEY');

const endpoint = 'https://api.lambdatest.com/screenshots/v1/';
const auth = 'Basic ' + Buffer.from(`${username}:${accessKey}`).toString('base64');
const headers = { Authorization: auth, Accept: 'application/json', 'Content-Type': 'application/json' };
const payload = {
  url: 'https://example.com',
  configs: [{ os: 'Windows 10', browser: 'Chrome', resolution: '1366x768' }]
};

const start = await fetch(endpoint, {
  method: 'POST', headers, body: JSON.stringify(payload)
});
if (!start.ok) throw new Error(`Start request failed with HTTP ${start.status}`);
const started = await start.json();
if (!started.test_id) throw new Error('Start response did not contain test_id');

const result = await fetch(`${endpoint}${encodeURIComponent(started.test_id)}`, { headers });
if (!result.ok) throw new Error(`Result request failed with HTTP ${result.status}`);
const data = await result.json();
console.log(data.status, data.screenshots);

Or skip the browser setup

For a direct screenshot response rather than a hosted cross-browser test matrix, ScreenshotNeo takes a URL in one API request and returns an image or PDF. It accepts cookie or consent banners like a visitor and removes 60+ known consent platforms, newsletter popups and chat widgets before capture; each of those steps can be turned off. Bot checks, blank pages and failed loads are never billed, and the response identifies the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information and PDF capture. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. See the ScreenshotNeo website and API documentation.

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://example.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

Troubleshooting

Symptom Likely cause What to do
401 or 403 response Missing, malformed or invalid Basic credentials, or account access restrictions. Confirm both environment variables are set correctly, check for whitespace or stale keys, and ensure the request uses Basic authentication. Never move credentials into the URL.
Start response has no test_id The response body differs from the expected success response, or the service returned an error payload. Inspect the HTTP status and response JSON safely. Do not assume every HTTP response is a successful submission.
400 response or rejected configuration A missing field, unsupported value, or malformed JSON/configuration. Compare field names and required values with the current start-test reference. Verify that the OS/browser/version and resolution are supported now.
GET result request fails The ID may be wrong, incomplete or copied from another submission; the endpoint path may be malformed. Use the exact test_id from the POST response and append it to the documented result endpoint.
Test or screenshot record is not successful The capture has not completed or that environment encountered a failure. Read the overall and per-record statuses. Recheck according to current service guidance if still processing; investigate the affected configuration if it failed.
Screenshot URL is absent or unusable The record may not be in a successful state, or the result data may not yet be ready. Check record status before consuming the URL. Retrieve the result again when the service indicates processing, and avoid assuming a URL exists on every record.
Request times out Network delay or a slow response. Choose a sensible client timeout for your application, record the job ID once received, and make retrieval a separate restartable operation. The sources do not specify a guaranteed runtime.

Reliability, performance and cost considerations

  • Separate submission from retrieval. Once you receive the test ID, persist it so a worker restart does not cause you to lose the handle to the job.
  • Handle HTTP and application status. Raise or branch on HTTP errors, parse the JSON, validate the ID, then inspect both test-level and screenshot-level status.
  • Keep the matrix purposeful. Each additional environment creates more outputs to handle. Select the OS, browser/version and resolution that address your compatibility question.
  • Plan for URL sensitivity. Screenshots and their URLs may expose page content. Keep result data out of public logs and follow your organization’s retention and access controls.
  • Check current limits and pricing. The research sources do not establish current price, job duration, exact catalog availability, or a fixed concurrency limit. Confirm these in the provider’s current documentation and account plan before estimating production cost.

FAQ

Can I use this API to capture several browser and operating system combinations?

Yes. Configure the test matrix in the request and review the resulting screenshot records by OS, browser, browser version and resolution. Confirm current supported combinations in the API reference.

Does the POST response contain the screenshot itself?

The documented workflow returns a test ID from submission. Retrieve the test details with GET, then inspect the screenshot records and their URLs.

Is this the same as a Selenium screenshot in Python?

No. Selenium controls a browser session you run or provision. This API submits a screenshot test to a hosted service and returns test results.

Are browser versions shown in older examples guaranteed to work?

No. Treat old configurations as examples of payload shape. Check the current platform catalog for availability.

References