Api reference

API de Templates

Gerenciar templates programaticamente - criar, listar, atualizar e deletar

API de Templates

Gerencie templates de forma programática com a API REST do RenderHub. Crie, liste, atualize e delete templates sem usar o Dashboard.

Visão Geral

A API de Templates permite:

  • ✅ Criar templates via API
  • ✅ Listar todos os templates
  • ✅ Buscar template específico
  • ✅ Atualizar template existente
  • ✅ Deletar template
  • ✅ Versionar templates

Base URL

https://renderhub.com/api/v1/templates

Autenticação

Todas as requisições requerem autenticação:

Authorization: Bearer SUA_CHAVE_API

Endpoints

POST /templates - Criar Template

Cria um novo template.

Request

POST /api/v1/templates
Content-Type: application/json
Authorization: Bearer rh_live_abc123...

Body Parameters

ParâmetroTipoObrigatórioDescrição
namestring✅ SimNome do template (único)
descriptionstring❌ NãoDescrição do template
contentstring✅ SimHTML do template com placeholders
categorystring❌ NãoCategoria: invoice, contract, report, certificate, other
variablesarray❌ NãoLista de variáveis esperadas
default_optionsobject❌ NãoOpções padrão de renderização

Exemplo

const response = await axios.post('https://renderhub.com/api/v1/templates', {
  name: 'invoice-v1',
  description: 'Template de fatura padrão',
  category: 'invoice',

  content: `
    <html>
      <head>
        <style>
          body { font-family: Arial; padding: 40px; }
          .header { border-bottom: 2px solid #333; }
          .total { font-size: 24px; font-weight: bold; }
        </style>
      </head>
      <body>
        <div class="header">
          <h1>{{company_name}}</h1>
          <p>Fatura #{{invoice_number}}</p>
        </div>

        <h2>Cliente</h2>
        <p>{{customer_name}}<br>{{customer_email}}</p>

        <h2>Itens</h2>
        <table>
          {{#each items}}
          <tr>
            <td>{{this.description}}</td>
            <td>{{this.quantity}}x</td>
            <td>R$ {{this.price}}</td>
          </tr>
          {{/each}}
        </table>

        <p class="total">Total: R$ {{total}}</p>
      </body>
    </html>
  `,

  variables: [
    { name: 'company_name', type: 'string', required: true },
    { name: 'invoice_number', type: 'string', required: true },
    { name: 'customer_name', type: 'string', required: true },
    { name: 'customer_email', type: 'string', required: false },
    { name: 'items', type: 'array', required: true },
    { name: 'total', type: 'string', required: true }
  ],

  default_options: {
    page_size: 'A4',
    orientation: 'portrait',
    margin_top: 20,
    margin_bottom: 20
  }
}, {
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  }
});

console.log('Template criado:', response.data.id);

Response (201 Created)

{
  "id": "tpl_7kj3h2g1k4j5h6",
  "name": "invoice-v1",
  "description": "Template de fatura padrão",
  "category": "invoice",
  "variables": [...],
  "default_options": {...},
  "version": 1,
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z"
}

GET /templates - Listar Templates

Lista todos os templates da conta.

Request

GET /api/v1/templates
Authorization: Bearer rh_live_abc123...

Query Parameters

ParâmetroTipoDescrição
categorystringFiltrar por categoria
pagenumberNúmero da página (padrão: 1)
limitnumberItens por página (padrão: 20, máx: 100)

Exemplo

const response = await axios.get('https://renderhub.com/api/v1/templates', {
  params: {
    category: 'invoice',
    page: 1,
    limit: 10
  },
  headers: {
    'Authorization': `Bearer ${API_KEY}`
  }
});

console.log(`Total de templates: ${response.data.total}`);
response.data.templates.forEach(tpl => {
  console.log(`- ${tpl.name} (${tpl.id})`);
});

Response (200 OK)

{
  "templates": [
    {
      "id": "tpl_7kj3h2g1k4j5h6",
      "name": "invoice-v1",
      "description": "Template de fatura padrão",
      "category": "invoice",
      "version": 1,
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:30:00Z"
    },
    {
      "id": "tpl_8ab4c5d6e7f8g9",
      "name": "contract-standard",
      "description": "Contrato padrão",
      "category": "contract",
      "version": 2,
      "created_at": "2024-01-10T09:00:00Z",
      "updated_at": "2024-01-14T15:20:00Z"
    }
  ],
  "total": 2,
  "page": 1,
  "limit": 10,
  "pages": 1
}

GET /templates/:id - Buscar Template

Obtém detalhes completos de um template específico.

Request

GET /api/v1/templates/tpl_7kj3h2g1k4j5h6
Authorization: Bearer rh_live_abc123...

Exemplo

const templateId = 'tpl_7kj3h2g1k4j5h6';

const response = await axios.get(`https://renderhub.com/api/v1/templates/${templateId}`, {
  headers: {
    'Authorization': `Bearer ${API_KEY}`
  }
});

console.log('Template:', response.data.name);
console.log('Variáveis:', response.data.variables);

Response (200 OK)

{
  "id": "tpl_7kj3h2g1k4j5h6",
  "name": "invoice-v1",
  "description": "Template de fatura padrão",
  "category": "invoice",

  "content": "<html>...</html>",

  "variables": [
    { "name": "company_name", "type": "string", "required": true },
    { "name": "invoice_number", "type": "string", "required": true }
  ],

  "default_options": {
    "page_size": "A4",
    "orientation": "portrait"
  },

  "version": 1,
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:00Z",

  "usage_count": 1234,
  "last_used_at": "2024-01-15T14:20:00Z"
}

PUT /templates/:id - Atualizar Template

Atualiza um template existente. Cria automaticamente uma nova versão.

Request

PUT /api/v1/templates/tpl_7kj3h2g1k4j5h6
Content-Type: application/json
Authorization: Bearer rh_live_abc123...

Body Parameters

Mesmos parâmetros do POST. Apenas campos fornecidos serão atualizados.

Exemplo

const templateId = 'tpl_7kj3h2g1k4j5h6';

const response = await axios.put(`https://renderhub.com/api/v1/templates/${templateId}`, {
  description: 'Template de fatura atualizado - v2',
  content: updatedHtmlContent,
  // Incrementa versão automaticamente
}, {
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json'
  }
});

console.log('Nova versão:', response.data.version);

Response (200 OK)

{
  "id": "tpl_7kj3h2g1k4j5h6",
  "name": "invoice-v1",
  "description": "Template de fatura atualizado - v2",
  "version": 2,
  "updated_at": "2024-01-16T10:00:00Z"
}

DELETE /templates/:id - Deletar Template

Deleta um template permanentemente.

Request

DELETE /api/v1/templates/tpl_7kj3h2g1k4j5h6
Authorization: Bearer rh_live_abc123...

Exemplo

const templateId = 'tpl_7kj3h2g1k4j5h6';

await axios.delete(`https://renderhub.com/api/v1/templates/${templateId}`, {
  headers: {
    'Authorization': `Bearer ${API_KEY}`
  }
});

console.log('Template deletado com sucesso');

Response (204 No Content)

Sem corpo na resposta. Status 204 indica sucesso.

Versionamento

Toda atualização de template cria uma nova versão automaticamente.

Obter Versões de um Template

GET /api/v1/templates/tpl_7kj3h2g1k4j5h6/versions

Response

{
  "template_id": "tpl_7kj3h2g1k4j5h6",
  "versions": [
    {
      "version": 2,
      "created_at": "2024-01-16T10:00:00Z",
      "changes": "Atualizado layout do cabeçalho"
    },
    {
      "version": 1,
      "created_at": "2024-01-15T10:30:00Z",
      "changes": "Versão inicial"
    }
  ]
}

Usar Versão Específica

// Renderizar com versão específica
const response = await axios.post('/api/v1/render', {
  mode: 'RENDER',
  template_id: 'tpl_7kj3h2g1k4j5h6',
  template_version: 1, // Usar versão 1 (antiga)
  data: { ... }
});

Variáveis do Template

Tipos Suportados

TipoDescriçãoExemplo
stringTexto simples"João Silva"
numberNúmero42
booleanVerdadeiro/Falsotrue
arrayLista de itens[{...}, {...}]
objectObjeto aninhado{ nome: "...", idade: 30 }
dateData ISO"2024-01-15"

Syntax de Template (Handlebars)

<!-- Variável simples -->
<p>{{customer_name}}</p>

<!-- Condicional -->
{{#if premium_customer}}
  <p>Cliente Premium</p>
{{else}}
  <p>Cliente Regular</p>
{{/if}}

<!-- Loop -->
{{#each items}}
  <li>{{this.name}} - R$ {{this.price}}</li>
{{/each}}

<!-- Helper de formatação -->
<p>Data: {{formatDate date "DD/MM/YYYY"}}</p>
<p>Valor: {{formatCurrency total "BRL"}}</p>

<!-- Variável com fallback -->
<p>{{customer_email}} ou "N/A"}}</p>

Helpers Disponíveis

HelperUsoExemplo
formatDateFormatar datas{{formatDate date "DD/MM/YYYY"}}
formatCurrencyFormatar moeda{{formatCurrency value "BRL"}}
uppercaseTexto em maiúsculas{{uppercase name}}
lowercaseTexto em minúsculas{{lowercase email}}
truncateTruncar texto{{truncate description 50}}

Validação de Template

Validar Antes de Criar

POST /api/v1/templates/validate
const response = await axios.post('https://renderhub.com/api/v1/templates/validate', {
  content: templateHtml,
  variables: [...]
}, {
  headers: { 'Authorization': `Bearer ${API_KEY}` }
});

if (response.data.valid) {
  console.log('✅ Template válido');
} else {
  console.error('❌ Erros:', response.data.errors);
}

Response

{
  "valid": false,
  "errors": [
    {
      "type": "syntax_error",
      "message": "Tag {{customer_name}} não fechada",
      "line": 42
    },
    {
      "type": "missing_variable",
      "message": "Variável 'total' usada mas não declarada",
      "variable": "total"
    }
  ]
}

Testar Template

Renderizar Teste

POST /api/v1/templates/:id/test
const response = await axios.post(`https://renderhub.com/api/v1/templates/${templateId}/test`, {
  data: {
    company_name: 'Empresa Teste',
    invoice_number: '2024-001',
    customer_name: 'Cliente Teste',
    total: 'R$ 1.000,00'
  }
}, {
  headers: { 'Authorization': `Bearer ${API_KEY}` }
});

// Retorna PDF de teste em base64
const testPdf = response.data.pdf_base64;

Categorias de Templates

CategoriaDescriçãoExemplos
invoiceFaturas e notas fiscaisFatura mensal, NF-e
contractContratos e acordosContrato de trabalho, NDA
reportRelatóriosRelatório mensal, dashboard
certificateCertificadosCertificado de conclusão
letterCartas e correspondênciasCarta de recomendação
receiptRecibosRecibo de pagamento
otherOutrosUso geral

Exemplos Práticos

Criar Template de Certificado

const certificate = await axios.post('/api/v1/templates', {
  name: 'certificate-course-completion',
  description: 'Certificado de conclusão de curso',
  category: 'certificate',

  content: `
    <html>
      <head>
        <style>
          body {
            text-align: center;
            padding: 100px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-family: 'Georgia', serif;
          }
          .border {
            border: 10px solid gold;
            padding: 50px;
          }
          h1 { font-size: 48px; margin-bottom: 40px; }
          .student { font-size: 36px; font-weight: bold; margin: 40px 0; }
        </style>
      </head>
      <body>
        <div class="border">
          <h1>CERTIFICADO</h1>
          <p>Certificamos que</p>
          <p class="student">{{student_name}}</p>
          <p>concluiu com sucesso o curso</p>
          <p style="font-size: 24px; font-weight: bold;">{{course_name}}</p>
          <p>com carga horária de {{course_hours}} horas</p>
          <p>em {{completion_date}}</p>
        </div>
      </body>
    </html>
  `,

  variables: [
    { name: 'student_name', type: 'string', required: true },
    { name: 'course_name', type: 'string', required: true },
    { name: 'course_hours', type: 'number', required: true },
    { name: 'completion_date', type: 'date', required: true }
  ],

  default_options: {
    page_size: 'A4',
    orientation: 'landscape'
  }
});

Criar Template de Relatório com Gráficos

const report = await axios.post('/api/v1/templates', {
  name: 'sales-report-monthly',
  category: 'report',

  content: `
    <html>
      <head>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
      </head>
      <body>
        <h1>Relatório de Vendas - {{month}}/{{year}}</h1>

        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px;">
          <div class="metric">
            <h3>Total de Vendas</h3>
            <p style="font-size: 32px;">{{formatCurrency total_sales "BRL"}}</p>
          </div>
          <div class="metric">
            <h3>Novos Clientes</h3>
            <p style="font-size: 32px;">{{new_customers}}</p>
          </div>
          <div class="metric">
            <h3>Taxa de Conversão</h3>
            <p style="font-size: 32px;">{{conversion_rate}}%</p>
          </div>
        </div>

        <canvas id="chart" width="800" height="400"></canvas>

        <script>
          new Chart(document.getElementById('chart'), {
            type: 'line',
            data: {
              labels: {{json sales_by_day.labels}},
              datasets: [{
                label: 'Vendas Diárias',
                data: {{json sales_by_day.values}}
              }]
            }
          });
        </script>
      </body>
    </html>
  `
});

Limites

RecursoLimitePlano Enterprise
Templates por conta100Ilimitado
Tamanho do template1 MB5 MB
Variáveis por template50Ilimitado
Versões mantidas10 últimasTodas

Códigos de Erro

CódigoErroDescrição
400template_name_requiredNome do template é obrigatório
400template_content_requiredConteúdo do template é obrigatório
400invalid_template_syntaxSintaxe inválida no template
409template_name_existsNome do template já existe
404template_not_foundTemplate não encontrado
413template_too_largeTemplate excede 1 MB

Próximos Passos

On this page