API Docs

AI Toolkit

Pricing

$0.25

API Docs

AI Toolkit

Changelog

Pricing

$0.25

All posts
Guides

How to e-sign a PDF programmatically in Python

Upload a PDF, place a signature field, send it for signing and download the signed result, using Python, the requests library and the SignatureAPI REST API.

This tutorial sends a PDF for signature from a Python script and saves the signed copy when it comes back. It uses the requests library and plain HTTP, so it fits into a Django view, a Flask route, a Celery task or a one-off script without changes.

You need Python 3.9 or later and a free SignatureAPI test key. Test envelopes send no email to recipients, carry a watermark and are not billed, so you can run every step here as often as you like.

Set up

Install the two libraries the tutorial uses. standardwebhooks is only needed for the webhook step at the end.

Terminal
pip install requests standardwebhooks

Keep the key in an environment variable, never in the source file.

Python
import os
import requests

API = "https://api.signatureapi.com/v1"
HEADERS = {"X-API-Key": os.environ["SIGNATUREAPI_KEY"]}

Upload the PDF

If your PDF is already at a public URL, skip this step and use that URL. If you don’t have a PDF at hand, download our sample service agreement; the coordinates later in this tutorial match it. Otherwise, upload the bytes. The upload endpoint takes the raw file as the request body and returns a url that you use as the document source.

Python
def upload_pdf(path: str) -> str:
    with open(path, "rb") as f:
        response = requests.post(
            f"{API}/uploads",
            headers={**HEADERS, "Content-Type": "application/pdf"},
            data=f,
        )
    response.raise_for_status()
    return response.json()["url"]

Uploads are limited to 4.5 MB and expire after 24 hours, which is plenty of time to create the envelope. For files you send again and again, store the upload or keep the file in your Dashboard library.

Decide where the signature goes

A place is an area on the document where a recipient acts. There are two ways to position one.

If you control the PDF, put the text [[client_signature]] where the signature should appear. SignatureAPI finds the placeholder and puts the signature field there. Make the text white and the signer won’t see it.

If the PDF comes from somewhere else, use a fixed position: the page number and the distance from the top and left edges, in points (1/72 of an inch). The example below uses fixed positions that match the sample service agreement’s client signature line and date. For your own file, adjust page, top and left.

Create the envelope

The envelope holds the document, the recipient and the places. This one has a signature place and a date place that SignatureAPI fills in with the day the signer finished.

Python
def send_for_signature(document_url: str, name: str, email: str) -> dict:
    body = {
        "title": "Service Agreement",
        "message": "Please review and sign the attached agreement.",
        "metadata": {"order_id": "ord_1042"},
        "documents": [
            {
                "url": document_url,
                "fixed_positions": [
                    {"place_key": "client_signature", "page": 1, "top": 152, "left": 190},
                    {"place_key": "signed_on", "page": 1, "top": 160, "left": 380},
                ],
                "places": [
                    {"key": "client_signature", "type": "signature", "recipient_key": "client"},
                    {"key": "signed_on", "type": "recipient_completed_date", "recipient_key": "client"},
                ],
            }
        ],
        "recipients": [
            {"key": "client", "type": "signer", "name": name, "email": email}
        ],
    }
    response = requests.post(f"{API}/envelopes", headers=HEADERS, json=body)
    response.raise_for_status()
    return response.json()

Run it:

Python
url = upload_pdf("service-agreement.pdf")
envelope = send_for_signature(url, "Jane Doe", "jane@example.com")
print(envelope["id"], envelope["status"])  # a UUID, then "processing"

The recipient gets an email with a link to sign. In test mode, open the envelope in the Dashboard and use the email preview to sign as Jane.

If the request is wrong, the API answers with a 4XX status and an RFC 7807 problem body (application/problem+json). Its type field is a URL that explains the error. Log the whole body; raise_for_status() alone hides the detail.

Wait for the signed PDF

When every recipient has signed, the envelope’s status becomes completed and SignatureAPI generates the deliverable: the signed PDF with an audit log. The deliverable moves from processing to generated, and then its url is a download link.

For a script, polling the envelope is fine:

Python
import time

def wait_for_deliverable(envelope_id: str) -> str:
    while True:
        envelope = requests.get(f"{API}/envelopes/{envelope_id}", headers=HEADERS).json()
        deliverable = envelope.get("deliverable") or {}
        if deliverable.get("status") == "generated":
            return deliverable["url"]
        time.sleep(30)

def download(url: str, path: str) -> None:
    with requests.get(url, stream=True) as response:
        response.raise_for_status()
        with open(path, "wb") as f:
            for chunk in response.iter_content(chunk_size=65536):
                f.write(chunk)

A production loop also needs to stop when the envelope ends as canceled or failed. Keep the interval long: API keys have rate limits.

Use a webhook in production

A web app should not poll. Register a webhook endpoint in the Dashboard and subscribe to deliverable.generated. The event’s data.url is a download link that expires after one hour, and data.envelope_metadata carries the order_id you set, so you know which record the PDF belongs to.

Webhook requests are signed following the Standard Webhooks specification. Verify the signature with the raw request body before you trust anything in it. Here is a Flask handler:

Python
from flask import Flask, request
from standardwebhooks.webhooks import Webhook

app = Flask(__name__)
wh = Webhook(os.environ["SIGNATUREAPI_WEBHOOK_SECRET"])

@app.post("/webhooks/signatureapi")
def signatureapi_webhook():
    event = wh.verify(request.get_data(as_text=True), dict(request.headers))
    if event["type"] == "deliverable.generated":
        order_id = event["data"]["envelope_metadata"]["order_id"]
        download(event["data"]["url"], f"signed/{order_id}.pdf")
    return "", 204

verify raises an exception when the signature doesn’t match. Deliveries can arrive out of order and are retried for up to 48 hours when your endpoint fails, so the handler should be safe to run twice for the same event. For long downloads, queue the work and answer quickly.

To try the handler on your laptop, npx signatureapi listen forwards test-mode events to it and saves the signing secret into your .env file.

Where to go next

The same request shape covers more than one signer, signing order, text inputs and checkboxes. The envelope reference lists every field, and the OpenAPI spec can generate a typed client if you prefer one to raw requests.

START FOR FREE

Ready to get started?
Create an account instantly, no credit card required.

Get Started