CPFHub.io

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 cpfhub

Ou 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âmetroTipoPadrãoDescrição
apiKeystring-Sua API Key (obrigatório)
timeoutint10000Timeout em milissegundos
baseUrlstringhttps://api.cpfhub.ioURL 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*:    CPFData

Tratamento 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.codee.statusCodeDescrição
CPF_NOT_FOUND404CPF não encontrado (sem consumo de crédito)
INVALID_CPF_FORMAT400Formato inválido
INVALID_CPF_DIGITS422Dígitos verificadores inválidos
MISSING_API_KEY401API Key ausente
INVALID_API_KEY401API Key inválida
RATE_LIMIT_EXCEEDED429Limite de taxa excedido
INSUFFICIENT_CREDITS403Sem 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


Atualizado em 12 de maio de 2026