SDK Nim
SDK oficial para Nim 2.0+ com async nativo, tipagem forte e sem dependências além da stdlib.
Instalação
bash
nimble install cpfhubOu adicione ao seu_projeto.nimble:
Nim
requires "cpfhub >= 1.0.0"Requerimentos: Nim 2.0+
Inicialização
Nim
import cpfhub
let client = newCPFHub(
apiKey = getEnv("CPFHUB_API_KEY"),
# timeout = 10_000, # opcional, em ms
)Parâmetros de newCPFHub
| Parâmetro | Tipo | Padrão | Descrição |
|---|---|---|---|
apiKey | string | - | Sua API Key (obrigatório) |
timeout | int | 10000 | Timeout em milissegundos |
baseUrl | string | https://api.cpfhub.io | URL base da API |
Métodos
await client.lookup(cpf: string): CPFHubResult
Nim
import asyncdispatch
proc main() {.async.} =
let result = await client.lookup("12345678909")
echo result.data.name # "João da Silva"
echo result.data.gender # "M"
waitFor main()Tipo de retorno:
Nim
type
CPFData* = object
cpf*: string
name*: string
nameUpper*: string
gender*: string # "M" | "F"
birthDate*: string # "DD/MM/AAAA"
day*: int
month*: int
year*: int
CPFHubResult* = object
success*: bool
data*: CPFDataTratamento de erros
Nim
import cpfhub, asyncdispatch
proc main() {.async.} =
try:
let result = await client.lookup("12345678909")
echo result.data.name
except CPFHubError as e:
echo e.code # "CPF_NOT_FOUND"
echo e.msg # "CPF not found in our database"
echo e.statusCode # 404
waitFor main()Códigos de erro
e.code | e.statusCode | Descrição |
|---|---|---|
CPF_NOT_FOUND | 404 | CPF não encontrado (sem consumo de crédito) |
INVALID_CPF_FORMAT | 400 | Formato inválido |
INVALID_CPF_DIGITS | 422 | Dígitos verificadores inválidos |
MISSING_API_KEY | 401 | API Key ausente |
INVALID_API_KEY | 401 | API Key inválida |
RATE_LIMIT_EXCEEDED | 429 | Limite de taxa excedido |
INSUFFICIENT_CREDITS | 403 | Sem créditos disponíveis |
Exemplos de integração
Servidor HTTP com asynchttpserver
Nim
import asyncdispatch, asynchttpserver, json, strutils
import cpfhub
let server = newAsyncHttpServer()
let cpfhub = newCPFHub(apiKey = getEnv("CPFHUB_API_KEY"))
proc handler(req: Request) {.async.} =
if req.url.path.startsWith("/cpf/"):
let cpf = req.url.path[5..^1]
try:
let result = await cpfhub.lookup(cpf)
await req.respond(Http200, $(%* result.data),
newHttpHeaders([("Content-Type", "application/json")]))
except CPFHubError as e:
await req.respond(
HttpCode(e.statusCode),
$(%* {"error": e.code}),
newHttpHeaders([("Content-Type", "application/json")]))
else:
await req.respond(Http404, "Not Found")
waitFor server.serve(Port(8080), handler)Script de linha de comando
Nim
import os, asyncdispatch
import cpfhub
let client = newCPFHub(apiKey = getEnv("CPFHUB_API_KEY"))
let cpf = if paramCount() > 0: paramStr(1) else: ""
if cpf == "":
echo "Uso: ./consulta <CPF>"
quit(1)
proc run() {.async.} =
try:
let r = await client.lookup(cpf)
echo "Nome: ", r.data.name,
" | Gênero: ", r.data.gender,
" | Nascimento: ", r.data.birthDate
except CPFHubError as e:
echo "Erro: ", e.code
quit(1)
waitFor run()Repositório e suporte
- github.com/cpfhub/cpfhub-nim - código-fonte, issues e contribuições
- nimble.directory/pkg/cpfhub - versões e changelog
Atualizado em 12 de maio de 2026