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âmetro | Tipo | Obrigatório | Descrição |
|---|---|---|---|
name | string | ✅ Sim | Nome do template (único) |
description | string | ❌ Não | Descrição do template |
content | string | ✅ Sim | HTML do template com placeholders |
category | string | ❌ Não | Categoria: invoice, contract, report, certificate, other |
variables | array | ❌ Não | Lista de variáveis esperadas |
default_options | object | ❌ Não | Opçõ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âmetro | Tipo | Descrição |
|---|---|---|
category | string | Filtrar por categoria |
page | number | Número da página (padrão: 1) |
limit | number | Itens 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
| Tipo | Descrição | Exemplo |
|---|---|---|
string | Texto simples | "João Silva" |
number | Número | 42 |
boolean | Verdadeiro/Falso | true |
array | Lista de itens | [{...}, {...}] |
object | Objeto aninhado | { nome: "...", idade: 30 } |
date | Data 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
| Helper | Uso | Exemplo |
|---|---|---|
formatDate | Formatar datas | {{formatDate date "DD/MM/YYYY"}} |
formatCurrency | Formatar moeda | {{formatCurrency value "BRL"}} |
uppercase | Texto em maiúsculas | {{uppercase name}} |
lowercase | Texto em minúsculas | {{lowercase email}} |
truncate | Truncar 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
| Categoria | Descrição | Exemplos |
|---|---|---|
invoice | Faturas e notas fiscais | Fatura mensal, NF-e |
contract | Contratos e acordos | Contrato de trabalho, NDA |
report | Relatórios | Relatório mensal, dashboard |
certificate | Certificados | Certificado de conclusão |
letter | Cartas e correspondências | Carta de recomendação |
receipt | Recibos | Recibo de pagamento |
other | Outros | Uso 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
| Recurso | Limite | Plano Enterprise |
|---|---|---|
| Templates por conta | 100 | Ilimitado |
| Tamanho do template | 1 MB | 5 MB |
| Variáveis por template | 50 | Ilimitado |
| Versões mantidas | 10 últimas | Todas |
Códigos de Erro
| Código | Erro | Descrição |
|---|---|---|
400 | template_name_required | Nome do template é obrigatório |
400 | template_content_required | Conteúdo do template é obrigatório |
400 | invalid_template_syntax | Sintaxe inválida no template |
409 | template_name_exists | Nome do template já existe |
404 | template_not_found | Template não encontrado |
413 | template_too_large | Template excede 1 MB |
Próximos Passos
- POST /render - Renderizar templates
- Modos de Operação - CONVERT vs RENDER
- Guia de Templates - Criar templates eficientes
- Exemplos - Exemplos completos