SDK .NET / C#
SDK oficial para .NET 6+ com suporte a async/await, tipagem forte e injeção de dependência via IServiceCollection.
Instalação
bash
dotnet add package CPFHub.SDKOu via Package Manager:
powershell
Install-Package CPFHub.SDKRequerimentos: .NET 6+
Inicialização
C#
using CPFHub;
var client = new CPFHubClient(new CPFHubOptions
{
ApiKey = Environment.GetEnvironmentVariable("CPFHUB_API_KEY")!,
// Timeout = TimeSpan.FromSeconds(10), // opcional
});Propriedades de CPFHubOptions
| Propriedade | Tipo | Padrão | Descrição |
|---|---|---|---|
ApiKey | string | - | Sua API Key (obrigatório) |
Timeout | TimeSpan | 00:00:10 | Timeout da requisição |
BaseUrl | string | https://api.cpfhub.io | URL base da API |
Métodos
await client.LookupAsync(string cpf)
Consulta um CPF e retorna os dados de identidade.
C#
var result = await client.LookupAsync("12345678909");
Console.WriteLine(result.Data.Name); // "João da Silva"
Console.WriteLine(result.Data.Gender); // "M"Retorno: CPFHubResult
C#
public record CPFHubResult(bool Success, CPFData Data);
public record CPFData(
string Cpf,
string Name,
string NameUpper,
string Gender, // "M" | "F"
string BirthDate, // "DD/MM/AAAA"
int Day,
int Month,
int Year
);Tratamento de erros
C#
using CPFHub;
using CPFHub.Exceptions;
try
{
var result = await client.LookupAsync("12345678909");
}
catch (CPFHubException ex)
{
Console.WriteLine(ex.Code); // "CPF_NOT_FOUND"
Console.WriteLine(ex.Message); // "CPF not found in our database"
Console.WriteLine(ex.StatusCode); // 404
}Códigos de erro
ex.Code | ex.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
ASP.NET Core - injeção de dependência
C#
// Program.cs
builder.Services.AddCPFHub(options =>
{
options.ApiKey = builder.Configuration["CPFHub:ApiKey"]!;
});C#
// Controllers/CPFController.cs
[ApiController]
[Route("[controller]")]
public class CPFController(ICPFHubClient cpfhub) : ControllerBase
{
[HttpGet("{cpf}")]
public async Task<IActionResult> Get(string cpf)
{
try
{
var result = await cpfhub.LookupAsync(cpf);
return Ok(result.Data);
}
catch (CPFHubException ex)
{
return StatusCode(ex.StatusCode, new { error = ex.Code });
}
}
}appsettings.json
JSON
{
"CPFHub": {
"ApiKey": "sua-api-key"
}
}Minimal API
C#
app.MapGet("/cpf/{cpf}", async (string cpf, ICPFHubClient client) =>
{
try
{
var result = await client.LookupAsync(cpf);
return Results.Ok(result.Data);
}
catch (CPFHubException ex)
{
return Results.Problem(ex.Code, statusCode: ex.StatusCode);
}
});Repositório e suporte
- github.com/cpfhub/cpfhub-dotnet - código-fonte, issues e contribuições
- NuGet: CPFHub.SDK - versões e changelog
Atualizado em 12 de maio de 2026