---
title: "Archive signed documents to SharePoint"
description: "Upload the signed PDF to a SharePoint document library through Microsoft Graph with app-only authentication when a deliverable is generated."
canonical: "https://signatureapi.com/docs/cookbook/archive-sharepoint-graph"
source: "https://signatureapi.com/docs/cookbook/archive-sharepoint-graph.md"
last_verified_api_version: "1.18.0"
last_modified: "2026-11-18T17:17:27Z"
---

# Archive signed documents to SharePoint

Upload the signed PDF to a SharePoint document library through Microsoft Graph with app-only authentication when a deliverable is generated.

_Last verified against API version 1.18.0._

Keep a copy of every signed document in a SharePoint document library. When `deliverable.generated` arrives, the handler gets a Microsoft Graph token as your app and uploads the PDF by path.

## What you need

- A webhook endpoint subscribed to `deliverable.generated` ([set up webhooks](https://signatureapi.com/docs/api/guides/how-to/set-up-webhooks)).
- A Microsoft Entra app registration with a client secret, and an administrator-granted application permission on Microsoft Graph.
- `SIGNATUREAPI_KEY`, `SIGNATUREAPI_WEBHOOK_SECRET`, `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET` and `SHAREPOINT_SITE_ID`.

## The handler

The sample uses the site's default document library and uploads with a single `PUT` for files up to 250 MB. A longer sample for larger files follows the notes.

```javascript Node.js
// npm install express standardwebhooks @azure/msal-node
import express from "express";
import { Webhook } from "standardwebhooks";
import { ConfidentialClientApplication } from "@azure/msal-node";

const msal = new ConfidentialClientApplication({
  auth: {
    clientId: process.env.AZURE_CLIENT_ID,
    clientSecret: process.env.AZURE_CLIENT_SECRET,
    authority: `https://login.microsoftonline.com/${process.env.AZURE_TENANT_ID}`,
  },
});

const app = express();

app.post("/webhooks/signatureapi", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = new Webhook(process.env.SIGNATUREAPI_WEBHOOK_SECRET).verify(
      req.body.toString("utf8"),
      req.headers,
    );
  } catch {
    return res.sendStatus(400);
  }
  if (event.type !== "deliverable.generated") return res.sendStatus(200);

  const { object_id: deliverableId, envelope_id: envelopeId } = event.data;

  // The link in the event expires after 1 hour, so fetch a fresh one.
  const api = await fetch(`https://api.signatureapi.com/v1/deliverables/${deliverableId}`, {
    headers: { "X-API-Key": process.env.SIGNATUREAPI_KEY },
  });
  const { url } = await api.json();
  const pdf = Buffer.from(await (await fetch(url)).arrayBuffer());

  const { accessToken } = await msal.acquireTokenByClientCredential({
    scopes: ["https://graph.microsoft.com/.default"],
  });

  const path = `signed/${envelopeId}/${deliverableId}.pdf`;
  const upload = await fetch(
    `https://graph.microsoft.com/v1.0/sites/${process.env.SHAREPOINT_SITE_ID}/drive/root:/${path}:/content`,
    {
      method: "PUT",
      headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/pdf" },
      body: pdf,
    },
  );
  if (!upload.ok) return res.sendStatus(500);
  res.sendStatus(200);
});

app.listen(3000);
```

```python Python
# pip install flask standardwebhooks requests msal
import os

import msal
import requests
from flask import Flask, request
from standardwebhooks import Webhook

graph_app = msal.ConfidentialClientApplication(
    os.environ["AZURE_CLIENT_ID"],
    client_credential=os.environ["AZURE_CLIENT_SECRET"],
    authority=f'https://login.microsoftonline.com/{os.environ["AZURE_TENANT_ID"]}',
)

app = Flask(__name__)


@app.post("/webhooks/signatureapi")
def handle():
    try:
        event = Webhook(os.environ["SIGNATUREAPI_WEBHOOK_SECRET"]).verify(
            request.get_data(), dict(request.headers)
        )
    except Exception:
        return "", 400
    if event["type"] != "deliverable.generated":
        return "", 200

    deliverable_id = event["data"]["object_id"]
    envelope_id = event["data"]["envelope_id"]

    # The link in the event expires after 1 hour, so fetch a fresh one.
    api = requests.get(
        f"https://api.signatureapi.com/v1/deliverables/{deliverable_id}",
        headers={"X-API-Key": os.environ["SIGNATUREAPI_KEY"]},
    )
    pdf = requests.get(api.json()["url"]).content

    token = graph_app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
    path = f"signed/{envelope_id}/{deliverable_id}.pdf"
    upload = requests.put(
        f'https://graph.microsoft.com/v1.0/sites/{os.environ["SHAREPOINT_SITE_ID"]}/drive/root:/{path}:/content',
        headers={
            "Authorization": f'Bearer {token["access_token"]}',
            "Content-Type": "application/pdf",
        },
        data=pdf,
    )
    return "", (200 if upload.ok else 500)
```

- Verify the signature over the raw body, as in [verify the signature](https://signatureapi.com/docs/api/guides/how-to/set-up-webhooks#verify-the-signature). Returning a non-2XX status makes SignatureAPI retry, for up to 48 hours.
- The same event can arrive more than once. The path combines the envelope id and the deliverable id, so a retry targets the same file.
- Both samples upload inline for brevity. For large volumes, acknowledge the event and move the upload to a job.
- MSAL's client credentials scope is always `https://graph.microsoft.com/.default`: it returns the application permissions an administrator granted. MSAL Python caches this token; the sample calls it on every event.
- Microsoft documents `Files.ReadWrite.All` as the least privileged application permission for the simple upload, and `Sites.ReadWrite.All` for upload sessions. Both reach every site. To limit the app to one site, use `Sites.Selected`: it starts with no access, and an administrator then grants your app a role such as `write` on the site with `POST /sites/{siteId}/permissions`. Granting it needs `Sites.FullControl.All`, or `Sites.Selected` with the `fullcontrol` or `owner` role. Test the upload with the exact permission you plan to ship.
- Replacing the contents of a file protected with a sensitivity label does not work with app-only authentication.

## Files over 250 MB

`PUT .../content` only supports files up to 250 MB. For larger files, create an upload session and send the bytes to the `uploadUrl` in ranges. Microsoft recommends sessions above 10 MiB, with ranges that are multiples of 320 KiB and under 60 MiB.

```javascript
const session = await fetch(
  `https://graph.microsoft.com/v1.0/sites/${siteId}/drive/root:/${path}:/createUploadSession`,
  {
    method: "POST",
    headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json" },
    body: JSON.stringify({ item: { "@microsoft.graph.conflictBehavior": "replace" } }),
  },
);
const { uploadUrl } = await session.json();

const chunk = 320 * 1024 * 30; // 9.375 MiB, a multiple of 320 KiB
for (let start = 0; start < pdf.length; start += chunk) {
  const end = Math.min(start + chunk, pdf.length);
  // No Authorization header here: the uploadUrl is pre-authenticated.
  const res = await fetch(uploadUrl, {
    method: "PUT",
    headers: { "Content-Range": `bytes ${start}-${end - 1}/${pdf.length}` },
    body: pdf.subarray(start, end),
  });
  if (!res.ok) throw new Error(`Upload failed at byte ${start}: ${res.status}`);
}
```

Send ranges in order. The last range returns `201 Created` or `200 OK`. `conflictBehavior` defaults to `fail` for upload sessions, so the sample sets `replace` to stay idempotent.

## Related

- [Deliverable events](https://signatureapi.com/docs/api/resources/events/deliverable-events#deliverablegenerated)
- [Get a deliverable](https://signatureapi.com/docs/api/resources/deliverables/get)
- [Webhooks](https://signatureapi.com/docs/api/webhooks)
- [Download signed documents](https://signatureapi.com/docs/api/guides/use-cases/save-signed-documents)
- Microsoft: [Upload small files](https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0), [Upload large files with an upload session](https://learn.microsoft.com/en-us/graph/api/driveitem-createuploadsession?view=graph-rest-1.0), [Selected permissions in OneDrive and SharePoint](https://learn.microsoft.com/en-us/graph/permissions-selected-overview), [Client credentials flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-client-creds-grant-flow)
