# Python - HTML to Image Example

Generate PNG, JPG, WebP, and PDF output with Python, using HTML/CSS or reusable templates rendered in Google Chrome.

## Generating images with Python

1.  Send your HTML/CSS to the API.
2.  The API renders it in Google Chrome.
3.  Read the generated image URL from the JSON response.

See [Creating an image](/getting-started/using-the-api/#creating-an-image) for request parameters. A response includes the image's `url` and `id`.

![Example image generated from HTML with Python](/assets/images/dog-rates-example.png)

## Authentication with Python

Use HTTP Basic authentication with your API ID as the username and API key as the password. Find both in the [dashboard](https://htmlcsstoimage.com/dashboard). Keep credentials in server-side configuration or environment variables.

## Python example code

The example sends a POST request to `https://hcti.io/v1/image`. Image creation requires `images:create`. See [authentication and API keys](/getting-started/using-the-api/api-keys/) for scoped credentials and access errors.

## Official PyPI client

For typed requests, responses, and signed URL helpers, use the official [`html-css-to-image`](https://pypi.org/project/html-css-to-image/) package.

```bash
pip install html-css-to-image
```

```python
from html_css_to_image import CreateHtmlCssImageRequest, HtmlCssToImageClient


with HtmlCssToImageClient("your-api-id", "your-api-key") as client:
    result = client.create_image(
        CreateHtmlCssImageRequest(
            html="<div class='box'>Python ✅</div>",
            css=".box { border: 4px solid #03B875; padding: 20px; }",
        )
    )


if result.success:
    print(result.url)
else:
    print(result.status_code, result.error)
```

The client also supports URL screenshots, templates, batches, image deletion, render options, and signed URLs. See the [Python client repository](https://github.com/htmlcsstoimage/python-client) for complete usage and API documentation.

## Direct HTTP example

```python
# pip3 install requests
import requests


HCTI_API_ENDPOINT = "https://hcti.io/v1/image"
# Retrieve these from https://htmlcsstoimage.com/dashboard
HCTI_API_USER_ID = 'your-user-id'
HCTI_API_KEY = 'your-api-key'


data = { 'html': "<div class='box'>Hello, world!</div>",
         'css': ".box { color: white; background-color: #0f79b9; padding: 10px; font-family: Roboto }",
         'google_fonts': "Roboto" }


image = requests.post(url=HCTI_API_ENDPOINT, data=data, auth=(HCTI_API_USER_ID, HCTI_API_KEY), timeout=60)
image.raise_for_status()


print("Your image URL is: %s"%image.json()['url'])
# https://hcti.io/v1/image/7ed741b8-f012-431e-8282-7eedb9910b32
```

## Need help?

Talk to a human. Email [support@htmlcsstoimage.com](mailto:support@htmlcsstoimage.com) and we’ll help you get started.
