Documentation API

Guide complet pour utiliser l'API Templatr

Introduction

Templatr est une API puissante pour générer des PDFs à partir de templates HTML. Notre API RESTful vous permet de télécharger des templates, de les gérer et de générer des PDFs personnalisés.

URL de base: https://api.templatr.com

Authentification

L'API Templatr supporte deux méthodes d'authentification :

Clé API (Recommandé pour les applications)

Shell
GET /api/pdf/template-id?api_key=YOUR_API_KEY

Note: Les clés API peuvent être créées depuis votre tableau de bord.

Endpoints disponibles

Télécharger un template

POST/upload
Shell
curl -X POST https://api.templatr.com/upload \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -F '[email protected]' \
  -F 'template_name=invoice_template'

Réponse:

{ "template_id": "abc123" }

Générer un PDF

POST/pdf/:template_id
Shell
curl -X POST https://api.templatr.com/pdf/abc123?api_key=YOUR_API_KEY \
  -H 'Content-Type: application/json' \
  -d '{
    "client_name": "John Doe",
    "invoice_number": "INV-001",
    "amount": 1500.00,
    "items": [
      { "description": "Service A", "price": 1000 },
      { "description": "Service B", "price": 500 }
    ]
  }' \
  --output invoice.pdf

Réponse: Fichier PDF binaire ou URL du PDF

Récupérer un template

GET/upload/:template_id
Shell
curl https://api.templatr.com/upload/abc123?api_key=YOUR_API_KEY

Mettre à jour un template

PUT/upload/:template_id
Shell
curl -X PUT https://api.templatr.com/upload/abc123?api_key=YOUR_API_KEY \
  -F 'file=@updated_template.html' \
  -F 'name=Updated Invoice Template'

Supprimer un template

DELETE/upload/:template_id
Shell
curl -X DELETE https://api.templatr.com/upload/abc123?api_key=YOUR_API_KEY

Exemples d'utilisation

JavaScript / Node.js
// Generate a PDF
const response = await fetch('https://api.templatr.com/pdf/abc123?api_key=YOUR_API_KEY', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    client_name: 'John Doe',
    invoice_number: 'INV-001',
    amount: 1500.00
  })
});

const pdfBlob = await response.blob();
// Save or display the PDF
Python
import requests

# Generate a PDF
data = {
    "client_name": "John Doe",
    "invoice_number": "INV-001",
    "amount": 1500.00
}

response = requests.post(
    "https://api.templatr.com/pdf/abc123",
    params={"api_key": "YOUR_API_KEY"},
    json=data
)

# Save the PDF
with open("invoice.pdf", "wb") as f:
    f.write(response.content)
Go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    // Data to send
    data := map[string]interface{}{
        "client_name":    "John Doe",
        "invoice_number": "INV-001",
        "amount":         1500.00,
    }

    jsonData, err := json.Marshal(data)
    if err != nil {
        panic(err)
    }

    // Create request
    req, err := http.NewRequest("POST", 
        "https://api.templatr.com/pdf/abc123?api_key=YOUR_API_KEY", 
        bytes.NewBuffer(jsonData))
    if err != nil {
        panic(err)
    }

    req.Header.Set("Content-Type", "application/json")

    // Send request
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    // Read response
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        panic(err)
    }

    // Save PDF
    err = os.WriteFile("invoice.pdf", body, 0644)
    if err != nil {
        panic(err)
    }

    fmt.Println("PDF saved successfully")
}
cURL
curl -X POST https://api.templatr.com/pdf/abc123?api_key=YOUR_API_KEY \
  -H 'Content-Type: application/json' \
  -d '{
    "client_name": "John Doe",
    "invoice_number": "INV-001",
    "amount": 1500.00
  }' \
  --output invoice.pdf
PHP
<?php
$data = [
    'client_name' => 'John Doe',
    'invoice_number' => 'INV-001',
    'amount' => 1500.00
];

$ch = curl_init('https://api.templatr.com/pdf/abc123?api_key=YOUR_API_KEY');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);

$response = curl_exec($ch);
curl_close($ch);

// Save the PDF
file_put_contents('invoice.pdf', $response);
?>

Exemple de template HTML

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; }
        .invoice-header { margin-bottom: 20px; }
        .amount { font-size: 24px; font-weight: bold; }
    </style>
</head>
<body>
    <div class="invoice-header">
        <h1>Facture #{{invoice_number}}</h1>
        <p>Client: {{client_name}}</p>
    </div>
    <div class="amount">
        Total: {{amount}} €
    </div>
    {{#if items}}
    <ul>
        {{#each items}}
        <li>{{description}} - {{price}} €</li>
        {{/each}}
    </ul>
    {{/if}}
</body>
</html>

Les templates utilisent la syntaxe Handlebars pour les variables et la logique.

Gestion des erreurs

L'API retourne des codes d'erreur HTTP standards :

200Succès
400Requête invalide (paramètres manquants ou invalides)
401Non authentifié (clé API invalide ou manquante)
403Interdit (quota dépassé)
404Ressource non trouvée
500Erreur serveur
{
  "error": "Invalid API key",
  "code": "INVALID_API_KEY"
}

Limites et quotas

Limites par défaut

  • Taille maximale du template : 10 MB
  • Taille maximale des données JSON : 1 MB
  • Timeout de génération PDF : 30 secondes
  • Quota mensuel : selon votre plan

Alerte quota : Vous recevrez un email d'alerte lorsque vous atteindrez 80% de votre quota mensuel.

Plans disponibles

Consultez notre page de tarification pour voir les différents plans et leurs quotas.