pythonrest

Error 415 when trying to merge PDFs by stirlingpdf.io with python


I am trying to merge two PDF files through the API of StirlingPDF with Python. Unfortunately, I always get an Error 415 back from the request (see below).

filepaths = [r"C:\Users\Public\Documents\data1.pdf",
             r"C:\Users\Public\Documents\data2.pdf"]

binary_data=[]
for filepath in filepaths:
    # read files in binary
    with open(filepath, 'rb') as file:
        binary_data.append(file.read())

    
url = "https://stirlingpdf.io/api/v1/general/merge-pdfs"

req_data ={"fileInput": binary_data, "sortType": "orderProvided", "removeCertSign": False}

# send a POST-request to API
response = requests.post(url, data=req_data)

I already tried the easiest get methods (get uptime) and they worked. As the documentation tells (API) i try to put it as a binary file to the API.

It should also be executed by the web-API, because the same code structure will be used in Python and VBA.

26.11.2024: The status of the webrequest is 415 'Unsupported Media Type' with the message "Content-Type 'application/json' is not supported."


Solution

  • Solved:

    filepaths = [r"C:\Users\Public\Documents\data1.pdf",
                 r"C:\Users\Public\Documents\data2.pdf"]
    
    fileout = r"C:\Users\Public\Documents\data3.pdf"
    
    url = "https://stirlingpdf.io/api/v1/general/merge-pdfs"
    
    # Create the files dictionary for the POST request
    files = []
    for i, filepath in enumerate(filepaths):
        with open(filepath, 'rb') as file:
            files.append(('fileInput', (f"file{i+1}.pdf", file.read(), 'application/pdf')))
    
    
    # Include any additional data as part of the form
    data = {
        "sortType": "orderProvided",
        "removeCertSign": False
    }
    
    # Make the POST request
    response = requests.post(url, files=files, data=data)
    
    
    # Check the response
    if response.status_code == 200:
        print("PDFs merged successfully!")
        # Optionally save the merged PDF
        with open(fileout, "wb") as output_file:
            output_file.write(response.content)
    else:
        print(f"Failed to merge PDFs: {response.status_code} - {response.text}")
    

    The biggest problem from my point of view, is that the documentation doesn´t show the form of documentlist.