CPFHub.io

Ruby on Rails

Consulte CPF em um Service Object usando Net::HTTP nativo. Sem gems adicionais.

Integrando com Cursor, Lovable, v0 ou outra IA?

Copie o prompt de integração e cole direto no seu assistente de IA - ele saberá exatamente como usar a API.

Abrir no Cursor

Pré-requisitos

  • Rails 6+
  • Uma API Key em app.cpfhub.io
  • Variável CPFHUB_API_KEY nas credentials ou no .env

Service Object

Crie app/services/cpf_lookup_service.rb:

Ruby
require 'net/http'
require 'json'

class CpfLookupService
  BASE_URL = 'https://api.cpfhub.io'

  Error   = Class.new(StandardError)
  NotFound = Class.new(Error)

  def self.call(cpf)
    new(cpf).call
  end

  def initialize(cpf)
    @cpf     = cpf
    @api_key = ENV.fetch('CPFHUB_API_KEY')
  end

  def call
    uri = URI("#{BASE_URL}/cpf/#{@cpf}")
    req = Net::HTTP::Get.new(uri)
    req['x-api-key'] = @api_key

    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |h| h.request(req) }
    body = JSON.parse(res.body)

    raise NotFound, body.dig('error', 'code') if res.code == '404'
    raise Error, body.dig('error', 'code')    unless res.is_a?(Net::HTTPSuccess)

    body['data']
  end
end

Controller

Ruby
class CpfController < ApplicationController
  def show
    data = CpfLookupService.call(params[:cpf])
    render json: { data: data }
  rescue CpfLookupService::NotFound
    render json: { error: 'CPF não encontrado' }, status: :not_found
  rescue CpfLookupService::Error => e
    render json: { error: e.message }, status: :unprocessable_entity
  end
end

Rota em config/routes.rb:

Ruby
get '/cpf/:cpf', to: 'cpf#show'

Campos retornados

CampoTipoExemplo
cpfstring"12345678909"
namestring"Fulano de Tal"
nameUpperstring"FULANO DE TAL"
gender"M" | "F""M"
birthDatestring"15/06/1990"
daynumber15
monthnumber6
yearnumber1990

Tratamento de erros

HTTPerror.codeDescrição
404CPF_NOT_FOUNDCPF não consta na base
422INVALID_CPF_DIGITSDígitos verificadores inválidos
429RATE_LIMIT_EXCEEDEDMuitas requisições
401UNAUTHORIZEDAPI Key inválida ou ausente

Links


Atualizado em 17 de maio de 2026