Jovemnf.WebAPI 1.0.2

dotnet add package Jovemnf.WebAPI --version 1.0.2
                    
NuGet\Install-Package Jovemnf.WebAPI -Version 1.0.2
                    
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="Jovemnf.WebAPI" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Jovemnf.WebAPI" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Jovemnf.WebAPI" />
                    
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 Jovemnf.WebAPI --version 1.0.2
                    
#r "nuget: Jovemnf.WebAPI, 1.0.2"
                    
#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 Jovemnf.WebAPI@1.0.2
                    
#: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=Jovemnf.WebAPI&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Jovemnf.WebAPI&version=1.0.2
                    
Install as a Cake Tool

Jovemnf.WebAPI 💎

.NET 9 License: MIT

Uma biblioteca .NET moderna, elegante e de alta performance para consumo de APIs HTTP. Inspirada na simplicidade, mas construída com o poder e a tipagem do .NET 9.

✨ Destaques

  • 🚀 Arquitetura Facade: Interface simplificada que esconde uma engenharia robusta.
  • 🏗️ Padrão Builder: Construção de requisições modular e segura.
  • 🛡️ Tipagem Forte: Suporte total a Generics e Nullable Reference Types.
  • 🧩 Zero Config: Funciona "out of the box", mas é totalmente extensível.
  • 🚦 HttpClient Optimized: Gerenciamento inteligente de instâncias do HttpClient.

🚀 Como Usar: API Estática (Estilo Axios)

A forma mais rápida e moderna de consumir APIs. Sem instanciamento, sem complicações. Todos os métodos estáticos retornam WebApiResponse<T> (veja Tipo de retorno abaixo).

GET Simples

var response = await Api.Get<Post>("https://api.example.com/posts/1");
Console.WriteLine(response.Content?.Title);
// response.StatusCode, response.Exception também disponíveis

POST com JSON

var data = new { title = "Meu Post", body = "Conteúdo legal", userId = 1 };
var result = await Api.Post<Post>("https://api.example.com/posts", data);
var post = result.Content;

Outros Verbos (PUT, PATCH, DELETE)

// Atualização parcial
var patchResponse = await Api.Patch("https://api.example.com/posts/1", new { title = "Novo Título" });

// Exclusão
var deleteResponse = await Api.Delete<bool>("https://api.example.com/posts/1");

🛠️ Modo Avançado (Fluente)

Para quando você precisa de controle granular sobre headers, timeouts e instâncias.

// Timeout em milissegundos (ex.: 15 segundos)
using var api = new Api("https://api.example.com", 15000)
    .WithHeaders(new Dictionary<string, string> { 
        { "Authorization", "Bearer my-token" },
        { "X-Custom-Header", "Value" }
    });

api.SetJson(new { filter = "active" });
var response = await api.Send<List<Data>>();
// response.Content, response.StatusCode, response.Exception

🔐 Autenticação

Basic Auth

using var api = new Api("https://api.exemplo.com")
    .WithBasicAuth("usuario", "senha");

var dados = await api.Send<Modelo>();

Certificados e mTLS

Para chamadas que exigem autenticação mTLS (Certificado Digital), você pode usar o método fluente .WithCertificate().

using var cert = new X509Certificate2("path/to/certificate.pfx", "password");

using var api = new Api("https://api.secure.com")
    .WithCertificate(cert);

var response = await api.Send<SecureData>();

Você também pode injetar seu próprio HttpClient se desejar:

using var api = new Api("https://api.example.com")
    .WithHttpClient(myCustomHttpClient);

📦 Tipo de retorno WebApiResponse

Todas as chamadas (estáticas e fluentes) retornam WebApiResponse<T>:

Propriedade Descrição
Content Corpo deserializado (tipo T) ou null em caso de erro/timeout.
StatusCode Código HTTP da resposta (ex.: HttpStatusCode.OK).
Exception Preenchido em timeout ou quando a resposta não foi sucesso (ex.: TimeoutException).

Em respostas de sucesso (2xx), use response.Content. Em falhas, a biblioteca lança exceções semânticas (veja abaixo); em timeout, o resultado vem em response.Exception sem lançar.


🛰️ Tratamento de Erros Inteligente

O Jovemnf.WebApi elimina a necessidade de verificar códigos de status manualmente o tempo todo. Ele mapeia automaticamente todos os códigos 4xx e 5xx para exceções específicas e semânticas.

Exemplos de Exceções Inclusas (> 40 tipos):

  • BadRequestException (400)
  • UnauthorizedAccessException (401)
  • ForbiddenException (403)
  • NotFoundException (404)
  • ConflictException (409)
  • UnprocessableEntityException (422)
  • InternalServerError (500)
  • BadGatewayException (502)
  • ProxyProhibited (quando a requisição é bloqueada por proxy, via WebException)

Para converter um HttpResponseMessage ou WebException em exceção semântica sem fazer a requisição, use Api.CheckException(response) ou Api.CheckException(webException).

try 
{
    var response = await Api.Get<User>(url);
    var user = response.Content;
}
catch (NotFoundException)
{
    // Lógica para usuário não encontrado
}
catch (UnauthorizedAccessException) 
{
    // Lógica para erro de login
}

📦 Instalação e Requisitos

  • Runtime: .NET 9.0+
  • Dependências:
    • Newtonsoft.Json: Para alta flexibilidade na serialização.
dotnet add package Jovemnf.WebAPI

Rodar os testes

Na raiz do repositório:

dotnet test

🏛️ Design Patterns Aplicados

Esta biblioteca foi refatorada seguindo princípios SOLID e padrões de projeto para garantir manutenibilidade:

  • Facade Pattern: Classe principal Api.
  • Builder Pattern: Internamente via WebRequestBuilder.
  • Strategy Pattern: Validação de respostas e lançamento de exceções.
  • Engine Pattern: Processamento centralizado via WebApiEngine.

© 2026 Wallace Silva - Desenvolvido com ❤️ e foco em qualidade.

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 (4)

Showing the top 4 NuGet packages that depend on Jovemnf.WebAPI:

Package Downloads
Rastreamos.Class

Package Description

CenterAlarm.CACM

Package Description

CenterAlarm.Auth

Package Description

RApp.Notifier

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 117 3/5/2026
1.0.1 107 3/3/2026
1.0.0 106 3/3/2026
0.0.6 8,960 3/25/2022
0.0.5 2,031 9/21/2018
0.0.4 1,639 8/24/2018
0.0.3 1,006 8/24/2018
0.0.2 1,032 8/18/2018
0.0.1 1,070 8/18/2018