October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Use the DocRaptor API with Python

A practical Python walkthrough for DocRaptor: install the client, authenticate safely, create and save a PDF, and choose synchronous or asynchronous generation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use DocRaptor’s official Python client to convert HTML or a URL into a PDF: install docraptor, set your API key as the client username, call create_doc, and write the returned bytes to a file in binary mode. Start with test mode while you verify the output; its PDFs are watermarked.

Install the DocRaptor Python client

Install or upgrade the package in the Python environment that will run your integration:

python -m pip install --upgrade docraptor

DocRaptor’s Python walkthrough uses the docraptor package and its DocApi client. See the official Python guide for the vendor’s setup example.

Generate a PDF from inline HTML

This runnable example sends HTML directly, enables test mode, and saves the response as a PDF. Set DOCRAPTOR_API_KEY in your environment to your account API key before running it.

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

api_key = os.environ["DOCRAPTOR_API_KEY"]
client = docraptor.DocApi()
client.api_client.configuration.username = api_key

try:
    response = client.create_doc({
        "test": True,
        "document_type": "pdf",
        "document_content": "<html><body><h1>Hello</h1></body></html>",
    })
    with open("document.pdf", "wb") as pdf_file:
        pdf_file.write(bytearray(response))
except docraptor.rest.ApiException as error:
    print("HTTP status:", error.status)
    print("Reason:", error.reason)
    print("Response body:", error.body)

Test-mode output is watermarked, so use it to validate the request and rendering rather than as a production deliverable. For production, set test to False and keep the API key outside source control—for example, in an environment variable or a secrets manager. The Python guide documents test generation and watermarking at DocRaptor’s Python guide.

Choose HTML content or a source URL

The request needs a document type and one source: either document_content or document_url. The API reference lists PDF, XLS, and XLSX as supported output types. The example above uses inline HTML; to render a URL instead, replace the source field like this:

response = client.create_doc({
    "test": True,
    "document_type": "pdf",
    "document_url": "https://example.com/report",
})

Use inline content when your application already has the HTML string. Use a URL when DocRaptor should retrieve a page hosted elsewhere. Ensure that any stylesheets, images, fonts, or other resources required for rendering are reachable in the context of the request.

For direct REST integrations, DocRaptor documents a JSON POST to https://api.docraptor.com/docs. Its documented HTTP Basic Authentication method uses the API key as the username and a blank password. The API overview also describes query-parameter authentication, but Basic Authentication is the documented choice for direct REST use. In the API reference, type is the current field name; document_type remains available for applications that use it. See the API overview and the API reference.

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

Handle the binary response and errors

A successful direct PDF response contains binary data, not printable text. Write it using wb mode, as in the example, or stream the bytes to the HTTP response or storage system your application uses. Opening a PDF in text mode can corrupt it.

When a request fails, the client raises docraptor.rest.ApiException. Log the status, reason, and response body to help diagnose the request, but do not log the API key or sensitive document contents. DocRaptor notes that error bodies may be XML; inspect the HTTP status and body rather than assuming every response is JSON. A successful PDF response may include the X-DocRaptor-Num-Pages header. The relevant response behavior is described in the API overview; exception fields are demonstrated in the Python guide.

Use asynchronous generation for long jobs

The Python guide describes synchronous generation with a 60-second limit and asynchronous generation with a 10-minute limit. These are DocRaptor’s stated service limits, not independent guarantees; check the current documentation before depending on them. For a document that may run longer than the synchronous window, use create_async_doc, then poll for completion or provide a callback URL to receive the result notification. See the Python guide for the current client pattern.

The asynchronous workflow changes how your application waits for and retrieves the result; it does not change the need to protect credentials or handle failures. Design the job so it can record the returned status identifier, resume checking later, and report an unsuccessful generation clearly to the caller.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Rendering options and version considerations

DocRaptor uses the Prince PDF engine. Its documentation highlights PDF capabilities such as mixed layouts, header placements, accessible PDF tagging, and crop marks. Many PDF-specific settings are Prince-specific, so consult the API reference and the relevant Prince documentation when you need specialized layout behavior.

DocRaptor accounts can use different Pipeline versions, which map to Prince and JavaScript versions. Rendering differences may therefore depend on the Pipeline selected for the account. Validate important documents against the version you actually use, especially after changing rendering settings or relying on engine-specific behavior.

Troubleshoot common problems

  • Authentication error: Confirm the account API key is set as client.api_client.configuration.username and that the environment variable contains the key without extra whitespace. Keep credentials out of code committed to a repository.
  • Missing document source: Provide either document_content or document_url, along with the document type. The API reference says the content field is required unless a URL is used.
  • The saved file is unreadable: Save response bytes in binary mode (wb); do not decode the response as text.
  • The PDF contains a watermark: The request is in test mode. Test documents are watermarked; use production mode for an unwatermarked production document.
  • Generation times out or takes too long: For jobs that may exceed the documented synchronous window, switch to create_async_doc and poll or use a callback. Check DocRaptor’s current limits before treating the guide’s time figures as guarantees.
  • Layout differs from expectations: Check that remote assets are accessible and that the account’s Pipeline version matches the one against which the output was validated. For specialized PDF layout features, check the Prince-specific options in the API reference.
  • The error is hard to interpret: Capture the exception’s status, reason, and body; DocRaptor notes that error bodies may be XML, so preserve the raw body in controlled logs.

Or skip the browser setup

DocRaptor is for generating documents from HTML or URLs. If what you need instead is a clean screenshot of a web page, ScreenshotNeo provides a one-request screenshot API and an MCP server for AI agents. It removes cookie banners, newsletter popups, and chat widgets before capture; bot checks, blank pages, and failed loads are never billed. Here is a Python request that saves a screenshot:

import requests

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

See the ScreenshotNeo API documentation for request options. It includes 1,000 screenshots per month free with no card, and paid plans start at $5 for 3,000. Sign up for ScreenshotNeo to start with the free monthly allowance.

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

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.