GenericRestClient 1.0.1
dotnet add package GenericRestClient --version 1.0.1
NuGet\Install-Package GenericRestClient -Version 1.0.1
<PackageReference Include="GenericRestClient" Version="1.0.1" />
<PackageVersion Include="GenericRestClient" Version="1.0.1" />
<PackageReference Include="GenericRestClient" />
paket add GenericRestClient --version 1.0.1
#r "nuget: GenericRestClient, 1.0.1"
#:package GenericRestClient@1.0.1
#addin nuget:?package=GenericRestClient&version=1.0.1
#tool nuget:?package=GenericRestClient&version=1.0.1
GenericRestClient
Cliente REST genérico para .NET 9.0 com suporte a autenticação, rate limiting e retry automático. Desenvolvido como solução para integração com APIs REST de forma resiliente e configurável.
📋 Sobre o Projeto
O GenericRestClient é uma biblioteca .NET que fornece uma abstração simplificada para realizar requisições HTTP com suporte nativo a:
- Autenticação: Bearer Token, OAuth2 e API Key
- Rate Limiting: Controle de taxa de requisições por minuto
- Retry Automático: Política configurável de retry com backoff exponencial/linear
- Resiliência: Tratamento automático de falhas transitórias usando Polly
🚀 Funcionalidades
Autenticação
- Bearer Token: Autenticação via token Bearer
- OAuth2: Suporte completo a OAuth2 com refresh automático de tokens
- API Key: Suporte a API Key via header ou query string
Rate Limiting
- Controle de requisições por minuto
- Fila automática de requisições
- Lança exceção quando limite é atingido
Retry/Backoff
- Retry automático para códigos 429 e 5xx
- Tratamento de exceções transitórias (timeout, DNS, etc.)
- Suporte a header
Retry-After - Backoff exponencial ou linear configurável
Operações HTTP
GET: Buscar recursosPOST: Criar recursosPUT: Atualizar recursosDELETE: Remover recursos
🔧 Instalação
Adicione o projeto GenericRestClient à sua solução.
🎯 Início Rápido
1. Configuração no appsettings.json
{
"ApiClient": {
"BaseUrl": "https://api.exemplo.com/",
"Authentication": {
"Enabled": true,
"Type": "OAuth2",
"GrantType": "client_credentials",
"ClientId": "seu-client-id",
"ClientSecret": "seu-client-secret",
"TokenEndpoint": "https://auth.exemplo.com/token",
"TokenRefreshSkewSeconds": 60
},
"RateLimit": {
"Enabled": true,
"RequestsPerMinute": 60
},
"Retry": {
"Enabled": true,
"MaxRetries": 3,
"BaseDelayMilliseconds": 500,
"UseExponentialBackoff": true
}
}
}
2. Registro no Program.cs
using GenericRestClient.Core;
using GenericRestClient.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = Host.CreateApplicationBuilder(args);
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
// Registrar RestClient
var httpClientBuilder = builder.Services.ConfigureGenericRestClient(builder.Configuration);
// Adicionar headers customizados (opcional)
httpClientBuilder.ConfigureHttpClient(client =>
{
if (!client.DefaultRequestHeaders.Contains("User-Agent"))
{
client.DefaultRequestHeaders.Add("User-Agent", "GenericRestClient/1.0");
}
});
// Configurar handlers
var options = builder.Configuration.GetSection("ApiClient")
.Get<GenericRestClient.Configuration.ApiClientOptions>();
// Authentication Handler
if (options?.Authentication?.Enabled == true)
{
var authType = options.Authentication.Type?.Trim().ToUpperInvariant();
switch (authType)
{
case "BEARER":
httpClientBuilder.AddBearerAuthentication();
break;
case "APIKEY":
httpClientBuilder.AddApiKeyAuthentication();
break;
case "OAUTH2":
httpClientBuilder.AddOAuth2Authentication();
break;
}
}
// RateLimit Handler
if (options?.RateLimit?.Enabled == true)
{
httpClientBuilder.AddRateLimit();
}
// Retry Handler
if (options?.Retry?.Enabled == true)
{
httpClientBuilder.AddRetry();
}
var host = builder.Build();
var client = host.Services.GetRequiredService<IRestClient>();
3. Uso do Cliente
// GET (não requer parâmetro genérico para request, apenas para response)
var user = await client.GetAsync<User>("users/123");
// POST
var newUser = new { Name = "João", Email = "joao@exemplo.com" };
var created = await client.PostAsync<object, User>("users", newUser);
// PUT
var updated = await client.PutAsync<object, User>("users/123", newUser);
// DELETE
await client.DeleteAsync("users/123");
📚 Estrutura do Projeto
GenericRestClient/
├── GenericRestClient/ # Biblioteca principal
│ ├── Core/ # IRestClient e RestClient
│ ├── Configuration/ # Opções de configuração
│ ├── Handlers/ # Handlers HTTP
│ │ ├── Authentication/ # Handlers de autenticação
│ │ ├── RateLimitHandler.cs
│ │ └── RetryHandler.cs
│ ├── Extensions/ # Extensões de configuração
│ └── Authentication/ # Providers de autenticação
├── GenericRestClient.Tests/ # Testes unitários
└── documentation/ # Documentação
├── Desafio Técnico...pdf # Especificação completa
└── RequestPipelineFlow.md # Fluxo de handlers
🔄 Fluxo de Requisições
O GenericRestClient utiliza o padrão DelegatingHandler do .NET para criar um pipeline de processamento:
Requisição → Retry → RateLimit → Authentication → HttpClient → Servidor
Resposta ← Retry ← RateLimit ← Authentication ← HttpClient ← Servidor
Para mais detalhes sobre o fluxo, consulte a documentação de fluxo de requisições.
🧪 Testes
O projeto inclui testes unitários na pasta GenericRestClient.Tests. Execute os testes com:
dotnet test
🛠️ Tecnologias Utilizadas
- .NET 9.0: Framework base
- Polly 8.6.4: Biblioteca de resiliência e retry
- Microsoft.Extensions.Http: Integração com HttpClientFactory
- Microsoft.Extensions.Options: Configuração baseada em opções
- System.Text.Json: Serialização JSON
📚 Referências
- Documentação do Desafio Técnico
- Fluxo de Requisições e Handlers
- Polly Documentation
- .NET HttpClient Documentation
🤝 Contribuindo
Este é um projeto de desafio técnico. Para sugestões ou melhorias, consulte a documentação de especificação.
Desenvolvido com .NET 9.0 🚀
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net9.0
- Microsoft.Extensions.Configuration (>= 9.0.10)
- Microsoft.Extensions.Http (>= 9.0.10)
- Microsoft.Extensions.Options (>= 9.0.10)
- Polly.Core (>= 8.6.4)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.