DniPeru
A Ruby gem that provides a unified interface to query DNI (Documento Nacional de Identidad) information from multiple Peruvian API providers.
Installation
Add this line to your application's Gemfile:
gem 'dni_peru'And then execute:
$ bundle install
Or install it yourself as:
$ gem install dni_peru
Getting Started
1. Get Your API Key
To use this gem, you need to register and get an API key from Decolecta:
- Visit https://decolecta.com/profile/
- Sign up for a free account
- Generate your API token
- Copy the token for configuration
2. Store Your API Key Securely
For Rails applications, add to your credentials:
EDITOR="code --wait" rails credentials:editAdd:
decolecta:
api_key: your_api_key_hereFor other applications, use environment variables:
export DECOLECTA_API_KEY="your_api_key_here"Or use a .env file with the dotenv gem.
Configuration
Configure the gem with your preferred settings and API keys:
DniPeru.configure do |config|
# Set the default provider (optional, defaults to :decolecta)
config.default_provider = :decolecta
# Set timeout in seconds (optional, defaults to 30)
config.timeout = 30
# Set API keys for different providers
config.set_api_key(:decolecta, ENV['DECOLECTA_API_KEY'])
config.set_api_key(:api_peru_dev, ENV['API_PERU_DEV_KEY'])
endQuick Start
require 'dni_peru'
# Configure with your API key
DniPeru.configure do |config|
config.set_api_key(:decolecta, 'your-api-key')
end
# Query a DNI
response = DniPeru.query('12345678')
if response.success?
puts "Nombre: #{response.nombre_completo}"
# => "Nombre: DOE SMITH, JOHN"
endUsage
Basic Usage
Query a DNI using the default provider:
response = DniPeru.query('12345678')
if response.success?
puts response.nombre_completo
# => "DOE SMITH, JOHN"
puts response.nombres
# => "JOHN"
puts response.apellido_paterno
# => "DOE"
puts response.apellido_materno
# => "SMITH"
puts response.dni
# => "12345678"
endUsing a Specific Provider
You can specify which provider to use for a query:
# Using decolecta.com (recommended)
response = DniPeru.query('12345678', provider: :decolecta)
# Using apiperu.dev
response = DniPeru.query('12345678', provider: :api_peru_dev)Using the Client Directly
For more control, you can create a client instance:
client = DniPeru::Client.new(provider: :decolecta)
response = client.query('12345678')
puts response.to_h
# => {
# dni: "12345678",
# nombres: "JOHN",
# apellido_paterno: "DOE",
# apellido_materno: "SMITH",
# nombre_completo: "DOE SMITH, JOHN",
# provider: "Decolecta"
# }Error Handling
The gem raises specific errors for different scenarios:
begin
response = DniPeru.query('12345678')
rescue DniPeru::InvalidDniError => e
puts "Invalid DNI format: #{e.message}"
rescue DniPeru::NotFoundError => e
puts "DNI not found: #{e.message}"
rescue DniPeru::UnauthorizedError => e
puts "Invalid API key: #{e.message}"
rescue DniPeru::RateLimitError => e
puts "Rate limit exceeded: #{e.message}"
rescue DniPeru::ConnectionError => e
puts "Connection failed: #{e.message}"
rescue DniPeru::ApiError => e
puts "API error: #{e.message}"
endSupported Providers
Decolecta (Recommended)
Provider identifier: :decolecta
- Website: https://decolecta.com/
- Documentation: https://decolecta.gitbook.io/docs
- Registration: https://decolecta.com/profile/
- Requires API key (register for free)
- Data source: RENIEC (official government registry)
- Security: HTTPS only, Bearer token authentication
- Features: DNI, RUC, Exchange rates
- Status monitor: https://status.apis.net.pe/
- Configuration:
config.set_api_key(:decolecta, 'your-api-key')
API Endpoint:
curl -H 'Accept: application/json' -H "Authorization: Bearer YOUR_TOKEN" \
'https://api.decolecta.com/v1/reniec/dni?numero=12345678'apiperu.dev
Provider identifier: :api_peru_dev
- Website: https://apiperu.dev/
- Requires API key
- Free tier: 100 queries/month
- Data source: SUNAT reduced registry and public sources
- Configuration:
config.set_api_key(:api_peru_dev, 'your-key')
Rails Integration
Initializer
Create an initializer file config/initializers/dni_peru.rb:
DniPeru.configure do |config|
config.default_provider = :decolecta
config.timeout = 30
config.set_api_key(:decolecta, Rails.application.credentials.dig(:decolecta, :api_key))
config.set_api_key(:api_peru_dev, Rails.application.credentials.dig(:api_peru_dev, :api_key))
endUsage in Models
class User < ApplicationRecord
validates :dni, presence: true, length: { is: 8 }
def fetch_dni_info
begin
response = DniPeru.query(self.dni)
update(
first_name: response.nombres,
paternal_surname: response.apellido_paterno,
maternal_surname: response.apellido_materno
)
rescue DniPeru::Error => e
errors.add(:dni, "Could not verify DNI: #{e.message}")
false
end
end
endUsage in Controllers
class UsersController < ApplicationController
def verify_dni
@response = DniPeru.query(params[:dni])
render json: @response.to_h
rescue DniPeru::Error => e
render json: { error: e.message }, status: :unprocessable_entity
end
endResponse Object
The Response object provides the following attributes:
-
dni- The DNI number -
nombres- First/given names -
apellido_paterno- Paternal surname -
apellido_materno- Maternal surname -
nombre_completo- Full name in format "PATERNAL MATERNAL, NAMES" -
provider- The provider used for the query -
raw_data- Raw data from the API response
Methods:
-
success?- Returns true if the query was successful -
to_h- Returns a hash representation of the response
Development
After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run bundle exec rake install.
Testing Your Configuration
Test your API configuration quickly:
export DECOLECTA_API_KEY='your-api-key'
ruby examples/test_config.rb 12345678Examples
The examples/ directory contains practical examples:
-
examples/basic_usage.rb- Basic gem usage examples -
examples/rails_integration.rb- Rails integration patterns (services, controllers, models, jobs) -
examples/test_config.rb- Configuration testing script
Testing
Run the test suite:
bundle exec rspecRun with coverage:
COVERAGE=true bundle exec rspecContributing
Bug reports and pull requests are welcome on GitHub at https://github.com/rubenpazch/dni-peru.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
License
The gem is available as open source under the terms of the MIT License.
Code of Conduct
Everyone interacting in the DniPeru project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.