How to Use APITemplate.io Images in a Python Script
Generate an image from an APITemplate.io template in Python with the v2 REST API, then retrieve its download URL. Learn how this differs from webpage screenshots.
To generate an image with APITemplate.io from Python, send an authenticated POST request to its v2 image endpoint, pass the image template ID in the query string, and send named element overrides as JSON. Read the generated image URL from the JSON response. APITemplate.io documents template-based image generation; its reviewed documentation does not establish a general-purpose endpoint for capturing an arbitrary webpage URL as a browser screenshot.
This distinction matters: if by “screenshot” you mean a rendered image of any live webpage, this APITemplate.io workflow does not show how to do that. It creates an image using a template you provide.
1. Prepare an image template and API credentials
- Create an APITemplate.io image template with the elements your script needs to fill.
- Note the template ID and the names of the elements you intend to override. The example below expects an element named
title. - Obtain your API key and keep it outside your source code, for example in environment variables.
- Install the Python dependency:
python -m pip install requests
The documented API uses the X-API-KEY request header. The default API base is https://rest.apitemplate.io/v2/; the image creation endpoint is create-image. APITemplate.io also documents regional endpoints for the US (the default), EU, Australia, and Singapore. Choose the documented regional base URL that fits your account or deployment needs.
2. Generate a template image with Python
Set the credentials and template ID in your environment before running the script. This example sends one text override and prints the returned image URL.
export APITEMPLATE_API_KEY="your_api_key"
export APITEMPLATE_TEMPLATE_ID="your_template_id"
python create_image.py
Save the following as create_image.py:
import os
import requests
API_KEY = os.environ["APITEMPLATE_API_KEY"]
TEMPLATE_ID = os.environ["APITEMPLATE_TEMPLATE_ID"]
url = f"https://rest.apitemplate.io/v2/create-image?template_id={TEMPLATE_ID}"
headers = {
"X-API-KEY": API_KEY,
"Content-Type": "application/json",
}
payload = {
"overrides": [
{"name": "title", "text": "Hello from Python"}
]
}
response = requests.post(url, headers=headers, json=payload, timeout=60)
response.raise_for_status()
result = response.json()
print(result["download_url"])
This example follows the documented endpoint, authentication header, JSON override shape, and successful-response field. It is illustrative and has not been executed against a live APITemplate.io account. Successful responses may include fields beyond download_url.
See APITemplate.io’s REST API reference and first API request guide for the current endpoint details. The current v2 documentation should be the reference for new integrations; the legacy v1 reference says v1 is no longer supported and recommends v2.
3. Save the generated image locally
The response provides a download_url. If your application needs a local file, make a second request to retrieve the image bytes. Keep error handling around both the generation request and the download request because they are separate network operations.
import os
from pathlib import Path
from urllib.parse import urlencode
import requests
API_KEY = os.environ["APITEMPLATE_API_KEY"]
TEMPLATE_ID = os.environ["APITEMPLATE_TEMPLATE_ID"]
api_url = "https://rest.apitemplate.io/v2/create-image"
response = requests.post(
api_url,
params={"template_id": TEMPLATE_ID},
headers={"X-API-KEY": API_KEY},
json={"overrides": [{"name": "title", "text": "Hello from Python"}]},
timeout=60,
)
response.raise_for_status()
result = response.json()
download_url = result["download_url"]
image_response = requests.get(download_url, timeout=60)
image_response.raise_for_status()
Path("generated-image.png").write_bytes(image_response.content)
print("Saved generated-image.png")
The filename extension should match the image format returned by the service. The documentation cited here establishes the download URL, but does not specify a universal output format for every template, so inspect the returned response or the endpoint’s current documentation when choosing a filename.
4. Configure the request correctly
| Part | What to provide | Common mistake |
|---|---|---|
| HTTP method | POST for REST image creation |
Using the separate Direct URL GET pattern as if it were the REST endpoint |
| Endpoint | v2 create-image endpoint |
Copying an obsolete v1 endpoint from old examples |
| Authentication | API key in X-API-KEY |
Putting the key in the JSON body or omitting it |
| Template selection | Template ID in the query string | Using a missing or incorrect ID |
| Overrides | JSON object with an overrides array of named values |
Sending a name that does not match an element in the template |
| Response handling | Parse JSON and read download_url |
Treating the REST response itself as the image bytes |
| Timeout | A finite client timeout suited to your request flow | Leaving a script waiting indefinitely |
Template overrides
Each override targets an element by name. The example uses a text property:
{"name": "title", "text": "Hello from Python"}
Use element names and property types that match your own template and the current API reference. The example does not establish the full set of overrideable element types or their property names.
Regional endpoint
The default base endpoint is the US endpoint. If selecting a region, replace the base URL with the appropriate regional URL listed in APITemplate.io’s getting-started documentation, while retaining the documented v2 image path. Do not guess a regional hostname; use the current official documentation.
Synchronous and asynchronous generation
Synchronous generation is documented as the default. APITemplate.io also describes an asynchronous option and webhook notification for larger or batch jobs. The precise async parameters can depend on the endpoint and are not established by the general example here. Check the current API reference before adding async behavior; do not assume that the synchronous request body can simply be reused unchanged.
5. Use the Direct URL route only when it fits
APITemplate.io documents a separate Direct URL image-generation route. It uses a GET URL containing a template ID, an auth code, and element-property query parameters. This can suit places that need an image URL, such as HTML, email, or Open Graph metadata, when that URL-based feature fits the use case.
Direct URL generation is distinct from the authenticated REST POST shown above. See the official Direct URL Image Generation guide for the URL structure and supported query parameters. Avoid logging or exposing URLs that contain credentials.
6. cURL and Node.js equivalents
These examples use the same documented REST request shape: API key header, template ID, and a JSON overrides array. They are translations of the documented pattern, not live-tested requests.
cURL
curl --request POST \
--url "https://rest.apitemplate.io/v2/create-image?template_id=${APITEMPLATE_TEMPLATE_ID}" \
--header "X-API-KEY: ${APITEMPLATE_API_KEY}" \
--header "Content-Type: application/json" \
--data '{"overrides":[{"name":"title","text":"Hello from cURL"}]}'
Node.js
const apiKey = process.env.APITEMPLATE_API_KEY;
const templateId = process.env.APITEMPLATE_TEMPLATE_ID;
if (!apiKey || !templateId) {
throw new Error("Set APITEMPLATE_API_KEY and APITEMPLATE_TEMPLATE_ID");
}
const endpoint = new URL("https://rest.apitemplate.io/v2/create-image");
endpoint.searchParams.set("template_id", templateId);
const response = await fetch(endpoint, {
method: "POST",
headers: {
"X-API-KEY": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
overrides: [{ name: "title", text: "Hello from Node.js" }],
}),
});
if (!response.ok) {
throw new Error(`APITemplate.io returned HTTP ${response.status}`);
}
const result = await response.json();
console.log(result.download_url);
7. Troubleshooting
| Symptom | Likely cause | What to check |
|---|---|---|
| Authentication error | The API key is absent, invalid, or sent in the wrong place. | Confirm the environment variable is set and the request has the X-API-KEY header. |
| Template not found or rejected | The template ID is wrong or unavailable to the account. | Check the ID and account access; keep it in the documented query parameter. |
| Override has no effect | The override name or property does not match the template element. | Compare the exact element name and supported property with the template and current API docs. |
| JSON parse error | The response is not the expected successful JSON body, or an intermediary returned another response. | Inspect the HTTP status and response body safely before parsing; do not print secrets. |
KeyError: 'download_url' |
The response may be an error payload or a different response shape. | Check status and JSON fields before indexing; consult the endpoint reference for the response. |
| Request times out | Generation took longer than the client timeout or network conditions delayed the response. | Choose a suitable finite timeout and review the documented async option for larger or batch jobs. |
| Old examples fail | They may use the legacy v1 API. | Use the current v2 reference; the legacy reference says v1 is no longer supported. |
| A webpage URL does not become a browser screenshot | This API flow is template-based image generation. | Use a browser screenshot service for arbitrary webpage capture, or build a browser-based capture workflow yourself. |
8. Performance, reliability, and cost considerations
- Network calls: Image generation returns JSON containing a download URL; saving the file requires a separate download request. Account for both operations in the time budget.
- Timeouts: Use an explicit timeout and handle timeout exceptions. For larger or batch workloads, review the currently documented asynchronous and webhook behavior rather than keeping a caller blocked indefinitely.
- Retries: Retry only errors that are plausibly transient, and use bounded retries with backoff in production. Confirm the endpoint’s current retry and duplicate-request semantics before automatically resubmitting a generation request.
- Secrets: Read API keys from a secret store or environment, restrict who can read them, and avoid placing credentials in source control, logs, or publicly accessible Direct URLs.
- Cost: The official documentation reviewed for this guide does not establish current plans, prices, or per-request charges. Check APITemplate.io’s current account or pricing information before estimating production cost.
- Limits: No throughput, latency, uptime, or request-volume figures are established by the sources used here. Do not size a production workload using invented benchmarks; confirm applicable limits with the provider.
9. Or skip the browser setup
If your actual task is capturing a live webpage, ScreenshotNeo is a website screenshot API and MCP server for developers. One GET request returns a PNG, JPEG, WebP, or PDF. The documented options include full-page capture, CSS element capture, device and viewport settings, custom CSS and JavaScript, wait conditions, cookies and headers, and more. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
Cookie banners are accepted like a visitor and removed, along with known newsletter popups and chat widgets, before capture; each cleanup step can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server gives AI agents tools for screenshots, page information, and PDF capture. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.
Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.
10. FAQ
Does APITemplate.io take a screenshot of any URL?
The cited documentation describes generating images from templates. It does not establish a generic browser screenshot endpoint for arbitrary webpages.
Can I use an official Python SDK?
APITemplate.io lists a Python library named apitemplateio-python, but the research used for this guide did not establish its current version or method signatures. The REST request avoids depending on unverified SDK details.
What should I use if I need an image template and a webpage screenshot?
Use the template API for template-driven graphics and a browser screenshot API for rendered pages. ScreenshotNeo is one such webpage screenshot API; its options and examples are in the documentation.
Where can I verify the current request and response format?
Use APITemplate.io’s REST API reference and first request guide. Check those pages again before relying on endpoint-specific asynchronous parameters or regional hostnames.


