Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Build a FastAPI endpoint that accepts a page URL, renders it with Playwright, and returns screenshot bytes with the correct image content type. The example below uses Playwright’s async Python API, shares one browser process through FastAPI’s lifespan, and creates and closes an isolated browser context for each request.

How do I build a screenshot API with FastAPI and Playwright?

This minimal service accepts a JSON object containing a URL and bounded capture options, then returns PNG, JPEG, or WebP bytes directly. The limits in the example are application choices, not limits imposed by FastAPI or Playwright; adjust them to fit your workload and security policy.

Install the dependencies and browser

In a Python environment, install FastAPI, Uvicorn, and Playwright, then install Chromium for Playwright:

python -m pip install fastapi uvicorn playwright
python -m playwright install chromium

Save the following as app.py. The endpoint requires a URL, defaults to a 1280 × 800 viewport and PNG, and optionally supports full-page capture. It returns image bytes without writing a temporary file.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
from contextlib import asynccontextmanager
from typing import Literal
from urllib.parse import urlsplit

from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel, Field
from playwright.async_api import async_playwright


MEDIA_TYPES = {
    "png": "image/png",
    "jpeg": "image/jpeg",
    "webp": "image/webp",
}


class ScreenshotRequest(BaseModel):
    url: str
    width: int = Field(default=1280, ge=320, le=2560)
    height: int = Field(default=800, ge=240, le=2560)
    full_page: bool = False
    image_type: Literal["png", "jpeg", "webp"] = "png"


@asynccontextmanager
async def lifespan(app: FastAPI):
    playwright = await async_playwright().start()
    browser = await playwright.chromium.launch()
    app.state.playwright = playwright
    app.state.browser = browser
    try:
        yield
    finally:
        await browser.close()
        await playwright.stop()


app = FastAPI(lifespan=lifespan)


@app.post("/screenshot")
async def screenshot(request: ScreenshotRequest):
    parsed = urlsplit(request.url)
    if parsed.scheme not in {"http", "https"} or not parsed.hostname:
        raise HTTPException(status_code=400, detail="url must be an absolute http or https URL")

    browser = app.state.browser
    context = await browser.new_context(
        viewport={"width": request.width, "height": request.height}
    )
    try:
        page = await context.new_page()
        await page.goto(request.url, wait_until="domcontentloaded", timeout=15_000)
        image = await page.screenshot(
            full_page=request.full_page,
            type=request.image_type,
        )
        return Response(content=image, media_type=MEDIA_TYPES[request.image_type])
    except Exception as exc:
        # Log the detailed exception server-side; do not expose internals to callers.
        raise HTTPException(status_code=502, detail="Page navigation or screenshot capture failed") from exc
    finally:
        await context.close()

Run the development server with:

uvicorn app:app --host 127.0.0.1 --port 8000

Send a request from another terminal:

curl -X POST http://127.0.0.1:8000/screenshot 
  -H 'Content-Type: application/json' 
  -d '{"url":"https://example.com","width":1280,"height":800,"full_page":true,"image_type":"png"}' 
  --output page.png

A successful request writes the returned PNG to page.png. Change the requested type and filename together for JPEG or WebP output. FastAPI passes a returned Response through directly, so the endpoint itself must supply the correct media type and valid response bytes; it does not serialize or validate the image body for you (FastAPI: Return a Response Directly).

What happens during a capture?

Reuse the browser, isolate each request

The FastAPI lifespan context starts Playwright and Chromium before the application serves requests, and closes them on shutdown. This is the documented lifecycle pattern for shared resources that need setup and cleanup (FastAPI: Lifespan Events). Each request gets its own browser context, which separates its page state from other captures; the finally block closes that context on both successful and failed captures.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Launching a fresh browser per request is another possible design, but it changes startup and resource costs. The example reuses a browser process; it does not establish a universal browser-pool size or performance advantage. Measure under your own load before deciding how to scale.

Choose when a page is ready

The example navigates with wait_until="domcontentloaded", which waits for the document’s DOM to be parsed. It does not guarantee that every image, font, animation, or client-side data request has finished. For pages that render content later, wait for a known selector or add an explicit bounded delay before taking the screenshot.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Playwright also supports waiting for network idle, but pages that maintain ongoing network activity may never reach that state. Select a readiness condition that matches the target page rather than applying one condition indiscriminately. Keep the navigation and any additional waits finite.

Which screenshot options should the API expose?

Playwright Python supports screenshot bytes, full-page captures, and screenshots of a specific locator (Playwright Python: Screenshots). Expose only the options your users need, validate their bounds, and avoid passing caller-controlled browser launch flags.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Need Implementation choice Trade-off
Capture the visible viewport Leave full_page false. Predictable capture area; content below the viewport is not included.
Capture the whole document Set full_page true. Includes content beyond the viewport but can produce much larger images and use more memory.
Capture one component Use a locator and call its screenshot method, such as await page.locator("main").screenshot(). Useful for focused captures; the selector must exist and identify the intended element.
Choose image encoding Use PNG, JPEG, or WebP and pair the format with its corresponding media type. Different formats have different output characteristics; choose based on the consumer’s requirements.
Return a small synchronous result Return the screenshot bytes directly in the HTTP response. Simple client flow; the caller waits for navigation and capture to finish.
Handle large or slow captures Consider storing an artifact and returning a job identifier or URL. Adds storage, lifecycle, and asynchronous job-management decisions.

For example, to capture a specific component instead of the page, replace the screenshot call with image = await page.locator("main").screenshot(type=request.image_type). If no matching element appears, handle that condition as a capture failure rather than returning an unrelated image.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What should change before exposing this endpoint publicly?

Treat caller-supplied URLs as a security boundary

A screenshot service that navigates to URLs supplied by callers can be abused to reach internal services or consume excessive resources. The scheme check in the example rejects malformed or non-HTTP(S) inputs; it is not an SSRF defense. For a public service, define an explicit destination policy that rejects loopback, private, link-local, and other internal addresses, accounts for DNS resolution and redirects, and restricts outbound network access where possible. Hostname validation alone is insufficient.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Also set service-level limits for capture duration, viewport and full-page output, concurrency, and request frequency. Authenticate callers if appropriate, avoid returning browser stack traces, and consider whether a synchronous response remains suitable for slow or large jobs. The right thresholds and storage or queue architecture depend on workload and threat model; there is no universal value established here.

Deploy with aligned browser dependencies

In a container, install the Playwright package, browser binaries, and required system dependencies. Pin the Playwright package and use a matching Playwright browser image or browser version: a mismatch can leave the package unable to locate its expected browser executable. Validate fonts, browser binaries, and system packages in the actual deployment environment (Playwright Python: Docker).

Playwright recommends using an init process in Docker to help avoid PID 1 zombie-process handling issues. For Chromium, its Docker guidance recommends --ipc=host because Chromium can run out of memory and crash without adequate shared memory. For crawling or scraping untrusted sites, follow the Docker guidance on running as a dedicated non-root user and using an appropriate seccomp profile; do not treat disabling browser sandboxing as a general production shortcut.

Troubleshooting common failures

  • Playwright cannot find Chromium: Install the browser with python -m playwright install chromium in the runtime image, and make sure the Playwright package and browser image versions match.
  • Navigation times out: The page may be slow, blocked, or waiting on ongoing activity. Keep a finite timeout, select a readiness condition suited to the page, and return a controlled error instead of an unbounded wait.
  • The response is mislabeled or unreadable: Match the response media type and filename to the selected format. A direct FastAPI Response is passed through, so the application is responsible for its content and headers.
  • The image is blank or missing late-loaded content: DOM readiness may occur before client-rendered elements appear. Wait for a page-specific selector or a bounded delay before capture.
  • Chromium crashes under container load: Check shared-memory configuration and use the recommended --ipc=host setting for Chromium where appropriate. Confirm the container has suitable memory for the workload.
  • Contexts or browsers remain open: Ensure context cleanup is in a finally path and close the shared browser and Playwright during application shutdown.
  • Callers can reach unintended destinations: A scheme-and-host parse check is not destination protection. Implement destination and outbound-network controls that account for private addresses, DNS resolution, and redirects.

Or skip the browser setup

If you need screenshots rather than a browser service to maintain, ScreenshotNeo is a website screenshot API with a one-request interface. For example, using the supplied cURL pattern:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and responses report the page verdict and billing status in headers. It also provides an MCP server with screenshot, page-info, and PDF-capture tools for AI agents. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots.

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

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.