Guides · Python · requests

Convert a URL to PDF in Python with requests

The baseline job: give the API a URL, get PDF bytes back. One POST, binary response, no callback dance — the body of the response is the file. Everything else on this page is about doing that reliably: auth, error handling, and not treating a JSON error as a PDF.

Below is a complete, runnable Python program using requests (pip install requests). It reads your API key from the SNAPDOK_KEY environment variable — free keys take about thirty seconds and need no card.

import os
import requests

resp = requests.post(
    "https://snapdok.io/v1/render",
    headers={"Authorization": "Bearer " + os.environ["SNAPDOK_KEY"]},
    json={
        "url": "https://your-app.com/report/42",
        "format": "pdf",
    },
    timeout=90,
)
resp.raise_for_status()

with open("page.pdf", "wb") as f:
    f.write(resp.content)

The response is the document itself with Content-Type: application/pdf. Errors come back as JSON with an error code — which is why every sample here checks the status before writing bytes to disk: the classic integration bug in every language is saving {"error":"UNAUTHORIZED"...} as report.pdf and discovering it a week later.

PDF rendering uses the page's print stylesheet and reflows to paper width, so the width parameter does not apply to PDFs (it is a screenshot concept). If a page looks wrong as PDF, its @media print CSS is usually the culprit. Repeated identical requests inside 24 hours are served from cache — X-Cache: HIT — and not charged.

Same endpoint, one more trick: if the page you are rendering has a form on it, adding "pdf_forms": true to a PDF render brings it back with real, fillable AcroForm fields — a PDF people can type into, not a picture of one. How that works.

Notes for requests

Three requests-specific details the sample already handles. resp.content is the binary body — resp.text would decode PDF bytes as text and corrupt them. raise_for_status() turns a JSON error response into an exception instead of letting it reach the open(..., "wb") call. And requests has no default timeout — without the explicit timeout= a hung connection blocks forever, which matters for a call that drives a real browser and legitimately takes seconds.

Response headers worth reading

HeaderMeaning
X-CacheHIT = served from the 24h cache, free.
X-RateLimit-RemainingRequests left in the current second.

Full parameter reference: the docs. Hard numbers on caps and timeouts: limits.

Related guides

Same task, other stacks

More with Python + requests