Use Playwright’s Chromium browser to render HTML in a FastAPI endpoint, then return the bytes from page.screenshot() in an image response. Set an explicit viewport, wait for the page’s actual content to be ready, and use full_page=True when the output should include the whole document. For production, reuse the browser process, isolate each request in its own context, and package Chromium and its system dependencies with the app.
What the FastAPI rendering flow does
HTML is not an image format: a browser must lay out the markup, apply CSS, load fonts and images, and run any JavaScript before it can be captured. Playwright controls Chromium for that work. FastAPI accepts the input, creates or navigates a page, waits for readiness, captures a PNG, and returns the PNG bytes with the correct content type.
For HTML supplied directly in a request, call page.set_content(). For a page already hosted at a URL, call page.goto(). In both cases, page.screenshot() returns image bytes when no output path is supplied, so the API does not need to write a temporary image file. Playwright’s Python screenshots guide documents byte output and full-page capture.
Install FastAPI, Playwright, and Chromium
Install the Python packages and the matching Playwright Chromium build in the same runtime environment that will run the API. Installing the Python package alone does not guarantee that the browser binary or its operating-system libraries are present.
#1 Best Overall
- 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.
python -m pip install fastapi uvicorn playwright
python -m playwright install chromium
For Linux containers, Playwright also provides an install command that installs browser dependencies along with Chromium:
python -m playwright install --with-deps chromium
Use a Docker image or deployment process that installs these dependencies reproducibly. A local development machine may already have system libraries that a minimal server image does not, so test the actual deployment image rather than relying only on a local run.
Build a FastAPI endpoint that returns PNG bytes
This example accepts either an HTML string or a URL, supports viewport dimensions, a full-page option, an optional CSS selector to capture, and a readiness selector. It starts one browser for the application lifespan and creates a fresh browser context for each request.
from contextlib import asynccontextmanager
from typing import Optional
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel, Field, model_validator
from playwright.async_api import async_playwright
class ScreenshotRequest(BaseModel):
html: Optional[str] = None
url: Optional[str] = None
width: int = Field(default=1280, ge=1, le=5000)
height: int = Field(default=800, ge=1, le=5000)
full_page: bool = False
selector: Optional[str] = None
wait_for_selector: Optional[str] = None
@model_validator(mode="after")
def require_one_input(self):
if bool(self.html) == bool(self.url):
raise ValueError("Provide exactly one of html or url")
return self
@asynccontextmanager
async def lifespan(app: FastAPI):
playwright = await async_playwright().start()
browser = await playwright.chromium.launch(headless=True)
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):
browser = app.state.browser
context = await browser.new_context(
viewport={"width": request.width, "height": request.height}
)
try:
page = await context.new_page()
page.set_default_timeout(15000)
page.set_default_navigation_timeout(30000)
if request.url:
await page.goto(request.url, wait_until="networkidle")
else:
await page.set_content(request.html, wait_until="networkidle")
if request.wait_for_selector:
await page.locator(request.wait_for_selector).wait_for(
state="visible", timeout=15000
)
if request.selector:
image_bytes = await page.locator(request.selector).screenshot(
type="png"
)
else:
image_bytes = await page.screenshot(
type="png", full_page=request.full_page
)
return Response(content=image_bytes, media_type="image/png")
except Exception as exc:
raise HTTPException(status_code=502, detail=f"Rendering failed: {exc}")
finally:
await context.close()
Save this as main.py and run it with Uvicorn:
uvicorn main:app --host 0.0.0.0 --port 8000
Send HTML directly with a JSON request:
curl -X POST http://localhost:8000/screenshot
-H 'Content-Type: application/json'
-d '{"html":"<html><body><h1>Hello</h1></body></html>","width":1280,"height":800}'
--output result.png
For a URL, replace the html field with "url":"https://example.com". The endpoint returns binary PNG content, not JSON; clients should save or stream the response body as an image.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #2
- 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.
Choose capture dimensions and scope
Viewport-sized output
The context viewport controls the browser’s layout width and height. Set both explicitly because responsive CSS, breakpoints, text wrapping, and image sizes depend on them. The viewport is measured in CSS pixels; it is not necessarily the final physical pixel dimensions on every display.
Full-page output
Set full_page=True to capture the full scrollable document rather than only the visible viewport. This is useful for reports and long HTML pages, though very tall pages can produce large image buffers and consume more memory. For pages with lazy-loaded images or sections that appear only after scrolling, full-page capture alone may not trigger every site’s loading behavior. If required content is missing, scroll through the page or use application-specific readiness logic before capturing.
Capture a single element
Use page.locator(selector).screenshot() when the API should return only a card, chart, invoice, or other component. The selected element must exist and be visible. An invalid selector, missing element, or element outside the expected state will time out or fail; return a clear client error in a production API rather than treating every rendering failure as an internal server problem.
Wait for dynamic content reliably
wait_until="networkidle" can be a useful starting point, but it is not a guarantee that application data is ready. Analytics, polling, persistent connections, or delayed client-side rendering can keep network activity alive—or finish before the visible content has been populated.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minutePC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #3
- 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.
Prefer a selector that represents the content being captured, such as #content-to-render, and wait for it to become visible. For stronger correctness, the application being rendered can expose a dedicated readiness marker only after data, fonts, and images needed in the output are available. Avoid using an arbitrary fixed sleep as the primary readiness mechanism: it can waste time on fast pages and still be too short on slow ones.
When accepting a selector from a caller, apply a bounded timeout. If it never appears, return a timeout response with enough context for the caller to correct the selector or page state. If the page is under your control, make the readiness signal part of the page contract.
Choose between self-hosting and a managed renderer
Self-hosted Playwright offers control over browser behavior, HTML, CSS, fonts, JavaScript, and network policy. The trade-off is that your service owns browser installation, memory use, concurrency, isolation, and upgrades. A Python wrapper such as html2image can simplify script-level captures from URLs, HTML strings, files, and CSS, but does not replace FastAPI request lifecycle and resource management.
For hosted screenshot services and APIs, ScreenshotNeo is the first alternative to consider: it removes cookie banners, popups, and chat widgets before capture, and only clean shots are billed.
| Approach | Useful when | Trade-offs |
|---|---|---|
| FastAPI with Playwright | You need control over browser setup, request handling, and rendering rules. | You maintain Chromium and its dependencies, enforce isolation, and manage memory and concurrency. |
| ScreenshotNeo API | You want a hosted screenshot endpoint rather than operating Chromium yourself. | Requests require an API key and depend on an external service. |
| Python html2image wrapper | You need a lightweight script or local utility around headless Chrome/Chromium. | It does not itself provide FastAPI lifecycle management or request isolation. |
Or skip the browser setup
ScreenshotNeo takes a URL in one GET request and returns an image or PDF. The following saves a WebP capture of a URL; see the ScreenshotNeo API documentation for request options and response behavior.
Rank #4
- 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
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
With ScreenshotNeo, cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed; and an MCP server lets AI agents use screenshot tools. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for the free plan.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Security, performance, and operating costs
Treat browser navigation as a security boundary
An endpoint that renders caller-provided URLs can be abused to make requests from your server to internal services. Validate schemes and destinations, block access to private and link-local network ranges, and consider enforcing outbound network restrictions outside the application. Do not assume that a syntactically valid URL is safe to visit.
For untrusted HTML, use isolated contexts and restrict browser permissions and network access. A separate context prevents ordinary page state such as cookies from carrying over between requests, but it is not a substitute for network controls or operating-system isolation. Limit input size, output dimensions, navigation time, and total request duration. Consider queueing or a separate worker pool when rendering may be slow.
Free tools Windows power users keep installed
One-click scans. No signup required.
Reuse the browser, not the page state
Starting Chromium for every request adds startup work and can sharply increase resource use. The example keeps a browser process open while creating and closing a context per request. This reuses the expensive browser while keeping cookies and page state separate. Set a concurrency limit: each active page consumes memory and CPU, and full-page or high-resolution screenshots can cost more than a small viewport capture.
Account for rendering dependencies
Fonts and remote assets affect layout and visual correctness. If a font fails to load, text may wrap differently; if an image is blocked or late, the capture may be incomplete. For controlled content, bundle assets or make them reliably available, then wait for the relevant readiness condition. Keep Chromium and Playwright versions aligned through the official installation process and validate captures after upgrades.
Best Value
- 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.
Troubleshooting common failures
- Chromium executable or shared-library error: install Chromium in the same environment as the application and install the required Linux dependencies. Test from the final container image.
- Navigation timeout: the target may be slow, unavailable, or never reach the chosen load condition. Set explicit bounded timeouts and choose a readiness signal that matches the page; do not remove all time limits.
- Network-idle wait never completes: persistent requests or polling may prevent an idle state. Navigate with a suitable earlier load condition, then wait for the visible content selector instead.
- Screenshot is blank or missing data: JavaScript may not have finished rendering, the wrong page or selector may be used, or the page may have failed. Check the final URL and page errors, and wait for an application-level ready element.
- Element screenshot fails: confirm the selector matches exactly one intended element and that it is visible. Use a bounded wait and return a useful error when the element is absent.
- Image dimensions are unexpected: check the context viewport and responsive breakpoints. Use
full_page=Truefor a whole document, or an element screenshot for a component rather than assuming the viewport controls capture height. - Memory spikes or slow responses: reduce concurrent renders, constrain dimensions and input size, avoid unnecessary full-page captures, and close every context in a
finallyblock. - Remote URL reaches an internal host: validate and restrict destinations before navigation, and enforce outbound network policy. URL parsing alone does not prevent server-side request forgery.
Return another image format
The example returns PNG using type="png" and the image/png media type. Playwright can also encode JPEG or WebP screenshots; if you add a request format option, validate it against the supported formats and set the response media type to match the bytes. Keep PNG as a sensible default for text-heavy output, while lossy formats may reduce payload size when that trade-off is acceptable.
Frequently Asked Questions
Can FastAPI return a screenshot without saving it to disk?
Yes. Playwright returns screenshot bytes directly, which FastAPI can place in a Response with an image media type.
Recommended Free Tools
Can I screenshot a Jinja2 template?
Yes. Render the template to an HTML string in your application, then pass that string to the page content flow before taking the screenshot.
Should I use a fixed delay before capturing?
Use a page-specific visible readiness selector when possible. A fixed delay is less reliable because rendering time varies.
Quick Recap
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.

