Use DocsFold PDF generation API with Python

This code makes a POST request to the DocsFold API with the required headers and request body to generate a PDF file from the specified template and overrides.

You need to replace YOUR_API_KEY with your actual API key and YOUR_TEMPLATE_ID with your actual template ID.

This code example includes parsing the JSON response and downloading the PDF file from the specified URL. The PDF file is then saved to disk with the name "invoice.pdf".

Note that you'll need to adjust the file path as needed for the output PDF.

You also need to have the requests library installed to run this code. You can install it using pip:

pip install requests
python
import requests
import json
# API endpoint and API key
url = "https://app.docsfold.com/api/v1/generate-pdf"
api_key = "YOUR_API_KEY"
template_id = "YOUR_TEMPLATE_ID"
# JSON data for the request body
data = {
"template": template_id,
"output_format": "url",
"overrides": {
"invoice_nr": "123",
"created_date": "January 1, 2022",
"due_date": "February 1, 2022",
"company_name": "Acme Corp",
"company_address": "Acme road, 1",
"company_postal_code": "Sunnyville, 1000",
"client_company_name": "Doe Corp",
"client_name": "John Doe",
"client_email": "john@doe.com",
"payment_method": "Check",
"payment_method_value": 1000,
"items": [
{
"name": "Website design",
"value": 300
},
{
"name": "Hosting (3 months)",
"value": 75
},
{
"name": "Domain name (1 year)",
"value": 10
}
]
}
}
# Headers with API key
headers = {
"Authorization": "Bearer " + api_key,
"Content-Type": "application/json"
}
# Make the request and get the response
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
# Parse the JSON response
json_response = json.loads(response.text)
# Check if the operation was successful
if json_response["status"] == "SUCCESS":
# Get the PDF URL and download the file
pdf_url = json_response["pdf_url"]
response = requests.get(pdf_url)
# Save the PDF file to disk
with open("output.pdf", "wb") as file:
file.write(response.content)
else:
# Print the error message
print("Error:", json_response["message"])
else:
print("Error: " + str(response.status_code) + " - " + response.reason + " - " + response.text)
Author Image
About the author

Gustavo Santos

Gustavo is the founder of DocsFold, based in Portugal. He has worked as a software developer for over 15 years. He enjoys exploring new technologies and using them to automate work as much as possible.