Démarrage rapide
Générez votre premier document — PDF ou DOCX — en moins de 5 minutes.
1. Obtenir votre clé API
Connectez-vous à DocPayload et ouvrez Dashboard > Settings > API access > Manage keys > Generate Key. Une clé est un Client ID et un Client secret : copiez le secret immédiatement, il n'est affiché qu'une seule fois. Notez aussi votre Tenant ID, affiché dans la même boîte de dialogue.
2. Obtenir un jeton d'accès
Échangez le Client ID et le secret contre un jeton d'accès :
curl -X POST https://api.docpayload.com/v1/api-auth/token -H "Content-Type: application/json" -d '{ "clientId": "YOUR_CLIENT_ID", "clientSecret": "YOUR_CLIENT_SECRET" }'
# { "access_token": "eyJhbGciOi...", "token_type": "Bearer", "expires_in": 3600, ... }
Tous les autres appels transmettent Authorization: Bearer YOUR_ACCESS_TOKEN. Le jeton est valable une heure : réutilisez-le jusqu'à son expiration plutôt que d'en demander un à chaque appel. Voir Authentification pour le détail.
3. Créer une définition de document
Une définition de document est un objet JSON qui décrit votre document. La même définition s'affiche au format PDF ou DOCX — vous choisissez le format au moment de la demande.
{
"document": {
"metadata": {
"title": "My First Document",
"author": "DocPayload"
},
"pageSetup": {
"size": "A4",
"orientation": "portrait",
"margin": [50, 40, 50, 40]
},
"styles": {
"title": { "fontSize": 22, "fontWeight": "bold", "color": "#1A1A2E" },
"body": { "fontSize": 11, "color": "#333333", "textAlign": "justify" }
},
"content": [
{ "p": "Hello from DocPayload!", "style": "title" },
{ "p": "This document was generated from a JSON definition using the DocPayload API. You can add [b]bold text[/b], [i]italic text[/i], [color, #0066CC]colored text[/color], tables, lists, images, barcodes, and much more.", "style": "body" }
]
}
}
4. Générer un document
Ajoutez /pdf ou /docx au point de terminaison pour choisir le format de sortie. PDF est le format par défaut s'il n'est pas spécifié. Les exemples ci-dessous utilisent /pdf ; chacun génère le document, puis le télécharge avec le même jeton.
- cURL
- C#
- JavaScript
- Python
curl -X POST https://api.docpayload.com/v1/{YOUR_TENANT_ID}/documents/generate-from-payload/pdf -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -H "Content-Type: application/json" -d @definition.json
# Téléchargez le fichier à l'adresse downloadUrl de la réponse, avec le même jeton
curl "DOWNLOAD_URL" -H "Authorization: Bearer YOUR_ACCESS_TOKEN" -o document.pdf
using var client = new HttpClient();
// Échanger la clé API contre un jeton d'accès
var tokenResponse = await client.PostAsJsonAsync(
"https://api.docpayload.com/v1/api-auth/token",
new
{
clientId = Environment.GetEnvironmentVariable("DOCPAYLOAD_CLIENT_ID"),
clientSecret = Environment.GetEnvironmentVariable("DOCPAYLOAD_CLIENT_SECRET"),
});
tokenResponse.EnsureSuccessStatusCode();
var token = (await tokenResponse.Content.ReadFromJsonAsync<JsonElement>())
.GetProperty("access_token").GetString();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
// Générer
var json = File.ReadAllText("definition.json");
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync(
"https://api.docpayload.com/v1/{YOUR_TENANT_ID}/documents/generate-from-payload/pdf", content);
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<JsonElement>();
var downloadUrl = result.GetProperty("downloadUrl").GetString();
// Télécharger avec le même jeton
var bytes = await client.GetByteArrayAsync(downloadUrl);
await File.WriteAllBytesAsync("document.pdf", bytes);
import { readFile, writeFile } from 'node:fs/promises';
// Échanger la clé API contre un jeton d'accès
const tokenResponse = await fetch('https://api.docpayload.com/v1/api-auth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
clientId: process.env.DOCPAYLOAD_CLIENT_ID,
clientSecret: process.env.DOCPAYLOAD_CLIENT_SECRET,
}),
});
const { access_token } = await tokenResponse.json();
const auth = { 'Authorization': `Bearer ${access_token}` };
// Générer
const response = await fetch('https://api.docpayload.com/v1/{YOUR_TENANT_ID}/documents/generate-from-payload/pdf', {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: await readFile('definition.json', 'utf8'),
});
const { downloadUrl } = await response.json();
// Télécharger avec le même jeton
const file = await fetch(downloadUrl, { headers: auth });
await writeFile('document.pdf', Buffer.from(await file.arrayBuffer()));
import os
import requests
# Échanger la clé API contre un jeton d'accès
token_response = requests.post(
"https://api.docpayload.com/v1/api-auth/token",
json={
"clientId": os.environ["DOCPAYLOAD_CLIENT_ID"],
"clientSecret": os.environ["DOCPAYLOAD_CLIENT_SECRET"],
},
)
token_response.raise_for_status()
auth = {"Authorization": f"Bearer {token_response.json()['access_token']}"}
# Générer
with open("definition.json", "rb") as f:
response = requests.post(
"https://api.docpayload.com/v1/{YOUR_TENANT_ID}/documents/generate-from-payload/pdf",
headers={**auth, "Content-Type": "application/json"},
data=f.read(),
)
response.raise_for_status()
download_url = response.json()["downloadUrl"]
# Télécharger avec le même jeton
file = requests.get(download_url, headers=auth)
file.raise_for_status()
with open("document.pdf", "wb") as out:
out.write(file.content)
L'appel de génération répond avec l'downloadUrl du document :
{
"status": "Succeeded",
"documentId": "a1b2c3d4e5f67890abcdef1234567890",
"fileName": "docpayload_v1-a1b2c3d4e5f67890abcdef1234567890.pdf",
"downloadUrl": "https://api.docpayload.com/v1/{YOUR_TENANT_ID}/assets/docs/docpayload_v1-a1b2c3d4e5f67890abcdef1234567890.pdf",
"fileSizeBytes": 29811,
"errorCodes": []
}
5. Ouvrir votre document
C'est tout ! L'downloadUrl exige le même en-tête Authorization: Bearer que tous les autres appels : récupérez-le avec le jeton et enregistrez les octets, comme le font les exemples. Ouvrir le lien dans un navigateur sans cet en-tête reçoit 401.
Fonctionne avec n'importe quelle pile
Vous venez de générer un document avec une requête HTTP standard. Remplacez /pdf par /docx pour changer de format — même définition, même appel API. Si votre pile peut envoyer du JSON avec POST, vous êtes prêt.
PHP avec curl_exec, Java avec HttpClient, Ruby avec Net::HTTP, Go avec net/http, WordPress avec wp_remote_post, systèmes hérités avec n'importe quelle bibliothèque HTTP — ils fonctionnent tous. Le code que vous venez de voir dans les exemples ci-dessus est tout ce dont vous avez besoin. Aucune bibliothèque spéciale à installer ou à mettre à jour.
Pointez votre IDE sur le Schéma JSON publié et vous obtiendrez l'autocomplétion sur chaque propriété et des soulignements rouges sur les fautes de frappe avant même de frapper l'API :
{
"$schema": "https://schemas.docpayload.com/v1/document-definition.schema.json",
"document": { "content": [{ "p": "Hello." }] }
}
Cette ligne dans votre fichier JSON est tout ce que la plupart des éditeurs ont besoin.
Étapes suivantes
- Document Definition — Apprenez le schéma complet
- Inline Formatting — Gras, italique, couleurs, images, codes-barres
- Data Binding — Créez des modèles réutilisables avec des données dynamiques
- Playground — Essayez-le en direct dans le navigateur