SDK e CLI
Frihet oferece um SDK oficial de TypeScript e uma CLI para gerenciar seu negócio a partir de código ou terminal. Ambos os pacotes estão publicados no npm.
| Pacote | npm | Uso |
|---|---|---|
@frihet/sdk | SDK para Node.js / TypeScript | |
frihet | CLI para terminal |
Instalação
SDK
npm install @frihet/sdk
CLI
npm install -g frihet
Autenticação
Você precisa de uma chave de API. Gere-a em Configurações > Segurança dentro de app.frihet.io. As chaves começam com fri_.
SDK
import Frihet from '@frihet/sdk';
const frihet = new Frihet({
apiKey: 'fri_live_...',
});
Opções adicionais:
| Opção | Tipo | Padrão | Descrição |
|---|---|---|---|
apiKey | string | -- | Sua chave de API (obrigatório) |
baseUrl | string | https://api.frihet.io/v1 | URL base da API |
timeout | number | 30000 | Timeout em milissegundos |
CLI
frihet login
# Insira sua chave de API interativamente
# Ou diretamente:
frihet login --key fri_live_...
A chave é salva em ~/.frihet/config.json com permissões 0600. Você também pode usar a variável de ambiente FRIHET_API_KEY.
SDK — Início rápido
Listar faturas
import Frihet from '@frihet/sdk';
const frihet = new Frihet({ apiKey: 'fri_live_...' });
const page = await frihet.invoices.list({ limit: 10, status: 'paid' });
console.log(`${page.total} faturas pagas`);
for (const inv of page.data) {
console.log(`${inv.documentNumber} — ${inv.clientName} — ${inv.total}`);
}
Criar uma fatura
const invoice = await frihet.invoices.create({
clientName: 'Acme S.L.',
items: [
{ description: 'Consultoria', quantity: 10, unitPrice: 150 },
{ description: 'Desenvolvimento web', quantity: 1, unitPrice: 3000 },
],
taxRate: 21,
dueDate: '2026-04-15',
});
console.log(`Fatura ${invoice.documentNumber} criada (${invoice.total} EUR)`);
Buscar e atualizar
// Busca por texto
const results = await frihet.clients.search('Acme');
// Atualizar um cliente
await frihet.clients.update(results.data[0].id, {
email: 'nuevo@acme.com',
fiscalZone: 'peninsula',
});
Marcar fatura como paga e enviar por email
await frihet.invoices.markPaid('inv_abc123');
await frihet.invoices.send('inv_abc123', {
recipientEmail: 'cliente@acme.com',
locale: 'es',
});
CLI — Início rápido
Ver status do negócio
frihet status
# Receita: EUR 12.500,00
# Despesas: EUR 3.200,00
# Líquido: EUR 9.300,00
frihet status --month 2026-02
Gerenciar faturas
# Listar faturas
frihet invoices list --status paid --limit 5
# Buscar
frihet invoices list -q "Acme"
# Ver detalhe
frihet invoices get inv_abc123
# Criar fatura
frihet invoices create --client "Acme S.L." --item "Consultoria,10,150" --tax 21
# Marcar como paga
frihet invoices paid inv_abc123
# Enviar por email
frihet invoices send inv_abc123 --to cliente@acme.com
Gerenciar despesas
# Listar despesas
frihet expenses list --from 2026-01-01 --to 2026-03-31
# Criar despesa
frihet expenses create --desc "Hospedagem mensal" --amount 49.99 --category software --vendor "Hetzner"
Gerenciar clientes
# Listar clientes
frihet clients list
# Buscar
frihet clients list -q "Acme"
# Criar cliente
frihet clients create --name "Acme S.L." --email info@acme.com --tax-id B12345678 --zone peninsula
Recursos disponíveis
O SDK expõe os seguintes recursos como propriedades da instância Frihet:
| Recurso | Propriedade | Métodos |
|---|---|---|
| Faturas | frihet.invoices | list, retrieve, create, update, del, search, markPaid, send, pdf, createBatch |
| Despesas | frihet.expenses | list, retrieve, create, update, del, search, createBatch |
| Clientes | frihet.clients | list, retrieve, create, update, del, search |
| Fornecedores | frihet.vendors | list, retrieve, create, update, del, search |
| Produtos | frihet.products | list, retrieve, create, update, del, search |
| Orçamentos | frihet.quotes | list, retrieve, create, update, del, search, pdf, send |
| Webhooks | frihet.webhooks | list, retrieve, create, update, del + verifySignature (estático) |
| Inteligência | frihet.intelligence | context, summary, monthly, quarterly |
Todos os métodos list e search retornam um objeto Page<T>:
interface Page<T> {
data: T[];
total: number;
limit: number;
offset: number;
}
Tratamento de erros
O SDK lança erros tipados para cada tipo de falha:
import Frihet, { AuthenticationError, NotFoundError, ValidationError, RateLimitError, TimeoutError } from '@frihet/sdk';
try {
await frihet.invoices.retrieve('no-existe');
} catch (err) {
if (err instanceof NotFoundError) {
console.log('Fatura não encontrada');
} else if (err instanceof AuthenticationError) {
console.log('Chave de API inválida');
} else if (err instanceof ValidationError) {
console.log('Dados inválidos:', err.message, err.details);
} else if (err instanceof RateLimitError) {
console.log(`Rate limit. Tentar novamente em ${err.retryAfter}s`);
} else if (err instanceof TimeoutError) {
console.log('Timeout');
}
}
| Classe | Código HTTP | Quando |
|---|---|---|
AuthenticationError | 401 | Chave de API inválida ou ausente |
NotFoundError | 404 | Recurso não encontrado |
ValidationError | 400 / 422 | Dados de entrada inválidos |
RateLimitError | 429 | Limite de requisições excedido |
TimeoutError | -- | Sem resposta no timeout configurado |
APIError | Outros | Erro genérico do servidor |
Retentativas automáticas
O SDK tenta automaticamente novamente as requisições que recebem códigos 429 (rate limit) ou 5xx (erro de servidor), até 3 vezes com backoff exponencial. Você não precisa implementar lógica de retentativas.
Idempotência
Para operações de criação, você pode enviar uma idempotencyKey para evitar duplicatas em caso de retentativas:
await frihet.invoices.create(
{ clientName: 'Acme S.L.', items: [{ description: 'Serviço', quantity: 1, unitPrice: 500 }] },
{ idempotencyKey: 'mi-clave-unica-123' }
);
Verificar webhooks
O SDK inclui um método estático para verificar a assinatura HMAC-SHA256 dos webhooks:
import { Webhooks } from '@frihet/sdk';
const isValid = Webhooks.verifySignature(
rawBody, // string ou Buffer do body
req.headers['x-frihet-signature'], // cabeçalho de assinatura
'whsec_tu_secreto', // segredo do webhook
);
Variáveis de ambiente
| Variável | Descrição |
|---|---|
FRIHET_API_KEY | Chave de API (alternativa a frihet login na CLI ou ao construtor do SDK) |
FRIHET_API_URL | URL base personalizada |
Mais informações
- API REST — referência completa de endpoints
- Webhooks — eventos e verificação de assinatura
- Repositório no GitHub — código-fonte, issues, contribuições
- npm @frihet/sdk | npm frihet