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.
Pré-requisitos
- Rails 6+
- Uma API Key em app.cpfhub.io
- Variável
CPFHUB_API_KEYnas 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
endController
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
endRota em config/routes.rb:
Ruby
get '/cpf/:cpf', to: 'cpf#show'Campos retornados
| Campo | Tipo | Exemplo |
|---|---|---|
cpf | string | "12345678909" |
name | string | "Fulano de Tal" |
nameUpper | string | "FULANO DE TAL" |
gender | "M" | "F" | "M" |
birthDate | string | "15/06/1990" |
day | number | 15 |
month | number | 6 |
year | number | 1990 |
Tratamento de erros
| HTTP | error.code | Descrição |
|---|---|---|
| 404 | CPF_NOT_FOUND | CPF não consta na base |
| 422 | INVALID_CPF_DIGITS | Dígitos verificadores inválidos |
| 429 | RATE_LIMIT_EXCEEDED | Muitas requisições |
| 401 | UNAUTHORIZED | API Key inválida ou ausente |
Links
Atualizado em 17 de maio de 2026