View all our code samples

Using Requests in Python

Requests is a popular Python HTTP library that provides a simple and elegant API for making HTTP requests and handling responses. It abstracts away the complexities of HTTP communication and provides features like automatic JSON parsing, session management, and response content decoding. requests is widely used for web scraping, API integration, and web development in Python.

We've implemented a code sample that you can re-use to convert your HTML documents to PDF, JPG, PNG or WEBP using PDFShift and Python:

import requests

def convert(api_key, params, endpoint='pdf'):
    """
    We focused on making this function as simple as possible.
    Since PDFShift is a REST API, we just need to send a
    POST request to the endpoint by passing a set of custom parameters.
    
    Args:
        api_key (str): Your API key.
        params (dict): A dictionary containing the parameters
                       you want to send to the API.
        endpoint (str): The type of conversion you want to perform
                        (pdf, png, jpg, webp)
    
    Returns:
        bytes | dict: Either the binary content of the PDF
                      or a dictionary containing the details
                      when filename/webhook are passed
    """
    
    assert endpoint in ('pdf', 'png', 'jpg', 'webp')
    
    response = requests.post(
        f'https://api.pdfshift.io/v3/convert/{endpoint}',
        auth=('api', api_key),
        json=params
    )
    response.raise_for_status()
    
    if 'filename' in params or 'webhook' in params:
        return response.json()
    
    return response.content

Here's how you can use the above code:

binary = convert('sk_XXXXXXXXXXXXXX', {'source': 'https://en.wikipedia.org/wiki/REST'})
with open('result.pdf', 'wb') as f:
    f.write(binary)

We've tested this code with the latest version of Requests and it's ready to be used in your project.

But if you were to encounter any bugs or issues while running it (or if you want to suggest changes to improve the code), please contact us and we'll be happy to help you out.