GenericRestClient 1.0.1

dotnet add package GenericRestClient --version 1.0.1
                    
NuGet\Install-Package GenericRestClient -Version 1.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="GenericRestClient" Version="1.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GenericRestClient" Version="1.0.1" />
                    
Directory.Packages.props
<PackageReference Include="GenericRestClient" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add GenericRestClient --version 1.0.1
                    
#r "nuget: GenericRestClient, 1.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package GenericRestClient@1.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=GenericRestClient&version=1.0.1
                    
Install as a Cake Addin
#tool nuget:?package=GenericRestClient&version=1.0.1
                    
Install as a Cake Tool

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 recursos
  • POST: Criar recursos
  • PUT: Atualizar recursos
  • DELETE: 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

🤝 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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.1 409 11/19/2025
1.0.0 403 11/19/2025