Skip to main content

Python Examples

Complete Python examples for using the DocGenLab API.

Installation

pip install requests

Basic Usage

Initialize Client

import requests
import os

class DocGenLabClient:
def __init__(self, api_key, base_url="https://api.docgenlab.com/api/v1"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}

def generate_document(self, template_id, input_data, output_format="pdf"):
"""Generate a single document"""
response = requests.post(
f"{self.base_url}/documents/",
headers=self.headers,
json={
"template_id": template_id,
"input_json": input_data,
"output_format": output_format
}
)
response.raise_for_status()
return response.json()

def get_document(self, document_id):
"""Get document status"""
response = requests.get(
f"{self.base_url}/documents/{document_id}",
headers=self.headers
)
response.raise_for_status()
return response.json()

def download_document(self, document_id, output_path):
"""Download generated document"""
response = requests.get(
f"{self.base_url}/documents/{document_id}/download",
headers=self.headers
)
response.raise_for_status()

with open(output_path, 'wb') as f:
f.write(response.content)

return output_path

# Initialize client
client = DocGenLabClient(api_key=os.getenv('DOCGENLAB_API_KEY'))

Example 1: Generate Invoice

# Generate invoice
document = client.generate_document(
template_id="invoice-template-id",
input_data={
"invoice_number": "INV-001",
"customer_name": "Acme Corp",
"amount": 1250.00,
"due_date": "2024-02-15",
"items": [
{"description": "Consulting", "quantity": 10, "price": 100},
{"description": "Support", "quantity": 5, "price": 50}
]
},
output_format="pdf"
)

print(f"Document created: {document['id']}")
print(f"Status: {document['status']}")

# Download when ready
if document['status'] == 'ready':
client.download_document(document['id'], 'invoice.pdf')
print("Downloaded invoice.pdf")

Example 2: With Webhook

from flask import Flask, request, jsonify

app = Flask(__name__)

# Webhook handler
@app.route('/webhooks/docgenlab', methods=['POST'])
def webhook_handler():
payload = request.json

if payload['status'] == 'completed':
# Download document from signed URL
import requests
response = requests.get(payload['download_url'])

# Save to file
with open(f"document_{payload['job_id']}.pdf", 'wb') as f:
f.write(response.content)

print(f"Document {payload['job_id']} saved!")

return jsonify({'status': 'ok'}), 200

if __name__ == '__main__':
app.run(port=5000)

Example 3: List Templates

def list_templates(client, is_uat=False):
"""List all templates"""
response = requests.get(
f"{client.base_url}/templates/",
headers=client.headers,
params={"is_uat": is_uat}
)
response.raise_for_status()
return response.json()

# Get production templates
templates = list_templates(client, is_uat=False)

for template in templates:
print(f"{template['name']} ({template['id']})")
print(f" Tokens: {[t['name'] for t in template['tokens_json']]}")

Example 4: Error Handling

import time

def generate_with_retry(client, template_id, input_data, max_retries=3):
"""Generate document with automatic retry on rate limit"""
for attempt in range(max_retries):
try:
doc = client.generate_document(template_id, input_data)
return doc
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429: # Rate limit
wait_time = 2 ** attempt # Exponential backoff
print(f"Rate limited. Retrying in {wait_time}s...")
time.sleep(wait_time)
else:
raise

raise Exception("Max retries exceeded")

# Usage
doc = generate_with_retry(client, "template-id", {"name": "John"})

Example 5: Async with asyncio

import asyncio
import aiohttp

class AsyncDocGenLabClient:
def __init__(self, api_key, base_url="https://api.docgenlab.com/api/v1"):
self.api_key = api_key
self.base_url = base_url
self.headers = {
"X-API-Key": api_key,
"Content-Type": "application/json"
}

async def generate_document(self, session, template_id, input_data):
async with session.post(
f"{self.base_url}/documents/",
headers=self.headers,
json={
"template_id": template_id,
"input_json": input_data,
"output_format": "pdf"
}
) as response:
return await response.json()

async def generate_multiple():
client = AsyncDocGenLabClient(api_key=os.getenv('DOCGENLAB_API_KEY'))

async with aiohttp.ClientSession() as session:
tasks = [
client.generate_document(session, "template-id", {"name": f"Customer {i}"})
for i in range(10)
]

results = await asyncio.gather(*tasks)

for result in results:
print(f"Generated: {result['id']}")

# Run
asyncio.run(generate_multiple())

Next Steps