How to Capture HTML Snippets with ScreenshotAPI
Render supplied HTML into an image or PDF with ScreenshotAPI. Learn when to use GET or POST, choose an output format, and handle timing and errors.
To capture an HTML snippet with ScreenshotAPI, send the markup in the custom_html parameter to its screenshot endpoint. The service renders that markup into an image or PDF; it does not return the original source as an HTML snippet. Use GET for short, URL-safe markup and POST with a JSON request body for longer documents. ScreenshotAPI documents that custom_html is rendered instead of loading a URL, and overrides the url option. See the endpoint documentation.
1. Get an API key and choose the request
Create or sign in to a ScreenshotAPI account and copy the API key from its dashboard. Keep the key on a server or in a secret manager; do not put a real key in browser JavaScript, a public repository, or a page delivered to users. Use a placeholder in examples.
| Situation | Request | Why |
|---|---|---|
| A tiny, static fragment with simple characters | GET with URL-encoded parameters | Easy to inspect and suitable for short query strings. |
| A full template, long markup, or content with many characters to encode | POST with JSON body | Keeps the HTML out of the URL and avoids URL-length truncation. |
GET query strings have practical length limits across clients, proxies, and servers. Encoding expands markup, especially where it contains spaces, quotes, CSS, or Unicode. If the snippet is more than a few lines, use POST rather than risk a truncated request.
2. Render a snippet with POST
This cURL example submits JSON and saves the image response as snippet.png. The dimensions control the output viewport; use the dimensions appropriate for the visual you need.
curl -X POST "https://shot.screenshotapi.net/v3/screenshot" \
-H "Content-Type: application/json" \
-d '{
"token": "YOUR_API_KEY",
"custom_html": "<div><h1>Hello</h1><p>Rendered snippet</p></div>",
"file_type": "png",
"output": "image",
"width": 1200,
"height": 630
}' --output snippet.png
The HTML characters are escaped here because JSON requires quotes and backslashes inside string values to be escaped. In application code, construct an object and let the JSON library serialize it; do not manually build a JSON string from arbitrary markup.
Python: send JSON and save image bytes
import requests
payload = {
"token": "YOUR_API_KEY",
"custom_html": "<div><h1>Hello</h1><p>Rendered snippet</p></div>",
"file_type": "png",
"output": "image",
"width": 1200,
"height": 630,
}
response = requests.post(
"https://shot.screenshotapi.net/v3/screenshot",
json=payload,
timeout=90,
)
response.raise_for_status()
with open("snippet.png", "wb") as image_file:
image_file.write(response.content)
Node.js: send JSON and save image bytes
import { writeFile } from "node:fs/promises";
const payload = {
token: "YOUR_API_KEY",
custom_html: "<div><h1>Hello</h1><p>Rendered snippet</p></div>",
file_type: "png",
output: "image",
width: 1200,
height: 630,
};
const response = await fetch("https://shot.screenshotapi.net/v3/screenshot", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
throw new Error(`ScreenshotAPI returned HTTP ${response.status}: ${await response.text()}`);
}
await writeFile("snippet.png", Buffer.from(await response.arrayBuffer()));
3. Use GET for a short snippet
For a compact snippet, let cURL encode each parameter rather than assembling an encoded URL yourself:
curl -G "https://shot.screenshotapi.net/v3/screenshot" \
--data-urlencode "token=YOUR_API_KEY" \
--data-urlencode 'custom_html=<div><h1>Hello</h1><p>Rendered snippet</p></div>' \
--data-urlencode "file_type=png" \
--data-urlencode "output=image" \
--data-urlencode "width=1200" \
--data-urlencode "height=630" \
--output snippet.png
Use an HTTP client’s query-parameter encoder in Python or Node.js as well. Encoding protects characters such as &, +, #, and non-ASCII text from being interpreted as URL syntax. If the markup becomes awkward to encode or approaches a request URL limit, switch to POST.
4. Choose image, JSON, or PDF output
ScreenshotAPI documents an image response and a JSON response mode. Choose the output mode and file type for the next step in your application:
| Format | Good fit | Trade-off |
|---|---|---|
| PNG | Text, sharp edges, or transparency | Lossless output can be larger than a lossy image. |
| JPG | Photo-heavy visuals where smaller files matter | Lossy compression does not preserve transparency. |
| WebP | Web delivery when the consuming clients support it | Check compatibility in the systems that will display or process the file. |
| A document intended to print, share, or paginate | It is a document artifact rather than a single raster image. |
These format descriptions follow ScreenshotAPI’s own feature guidance. A format is not universally best: choose based on fidelity, transparency, file size, client support, and whether the output should be a paginated document. See its feature documentation.
When the endpoint is configured for JSON output, handle the response as JSON according to the documented response schema instead of writing the response body as though it were image bytes. The image examples above deliberately request output=image and save the response body directly.
5. Make the rendered result complete
Static markup can render immediately, but scripts, animations, remote fonts, and asynchronous content may not be ready when the capture starts. If a result is blank or incomplete, ScreenshotAPI documents three timing strategies:
- Fixed delay: allow a known animation or slow script time to finish.
- Wait for a selector: wait for a CSS selector that appears when the snippet is ready.
- Wait for network activity to settle: use this when content arrives from asynchronous requests.
Use the narrowest condition that represents readiness. A fixed delay is simple but adds the same wait to every request and can still be too short. A readiness selector is more targeted if your markup controls when it appears. Network-idle waiting can be useful for request-driven content, but pages with continuing requests may never settle. Consult the endpoint documentation for the exact parameter names and supported values before adding a timing option.
If a matching capture may be served from cache but the current output is required, ScreenshotAPI’s getting-started documentation describes fresh=true for requesting a fresh capture. Read the getting-started guide.
6. Troubleshoot common failures
| Symptom | Likely cause | What to do |
|---|---|---|
| Request fails authentication | The token is missing, mistyped, or not the account’s API key. | Copy the key from the account dashboard, check the field name and request body, and keep the live key private. |
| Image is blank or missing later content | Capture began before scripts, animation, or asynchronous content completed. | Add a documented delay, selector wait, or network-idle wait that matches how the content becomes ready. |
| Request is rejected or markup is cut off | A long GET query exceeded a URL limit, or the body is invalid JSON. | Use POST for longer HTML. Send a JSON object through a serializer and set Content-Type: application/json. |
| Special characters disappear or change | Query-string characters were not encoded or JSON string characters were manually escaped incorrectly. | Use --data-urlencode with cURL, query parameter APIs for GET, and JSON serialization for POST. |
| Saved file is not a viewable image | The response may be an error or JSON response saved with an image extension. | Check the HTTP status and response mode before writing bytes; request output=image for the binary image workflow. |
| Old visual appears | A matching result may be cached. | Request fresh=true when you need a newly generated capture, as documented in the getting-started guide. |
| PDF does not match a single-image layout | PDF is a paginated document format. | Choose PDF for a printable document; choose PNG, JPG, or WebP for a raster visual. |
7. Keep the capture reliable and economical
- Choose POST for documents. It avoids query-string expansion and truncation problems for long markup.
- Wait for a real readiness signal. A useful selector or appropriate network condition avoids both premature captures and unnecessary fixed delays.
- Request only the needed artifact. Use image output for image bytes and JSON only when the application needs the documented structured response.
- Use cache deliberately. Reuse a cached matching result when freshness is not needed; use
fresh=truewhen it is. - Protect credentials and bound timeouts. Keep the key server-side and set a client timeout so a capture request cannot wait indefinitely from the caller’s perspective.
Rendering work and output size depend on the markup and selected artifact. Large documents and waits can take longer than a small static snippet. The cited ScreenshotAPI materials do not establish a universal latency, cost per capture, or performance guarantee, so check the service’s current account and pricing information for applicable limits and charges.
8. Screenshot an existing webpage instead
This guide sends your own HTML with custom_html. If you instead need a visual of a live webpage, use a webpage capture API with the target URL as input. If you need the page’s extracted text or HTML content, that is a separate extraction operation, not a screenshot response.
Or skip the browser setup
ScreenshotNeo is a website screenshot API and MCP server for developers. Its one-call API captures a URL as PNG, JPEG, WebP, or PDF. It captures webpages rather than accepting an HTML snippet as custom_html, so use the ScreenshotAPI method above when the input is markup you already have. ScreenshotNeo’s API documentation lists its request options.
curl -G "https://api.screenshotneo.com/v1/shot" \
-d access_key=YOUR_API_KEY \
--data-urlencode url=https://stripe.com \
-o shot.webp
ScreenshotNeo removes cookie and consent banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed. Its MCP server lets AI agents use screenshot, page-info, and PDF tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo’s free plan to get 1,000 screenshots a month with no card.
FAQ
Does ScreenshotAPI return my HTML snippet?
No. The custom_html input is rendered into an image or PDF; it is not an HTML-source extraction response.
Can I use HTML and a URL in the same request?
custom_html renders supplied markup instead of loading a URL and overrides the url option. Choose the input mode that matches what you want rendered.
Should I use GET or POST for HTML?
Use GET for short snippets that encode safely. Use POST for long markup to avoid query-string length limits and truncation.
Can I produce a PDF?
Yes. Select PDF as the file type when you need a document output; use an image type for a raster screenshot.


