All Projects → nclient → NClient

nclient / NClient

Licence: Apache-2.0 license
💫 NClient is an automatic type-safe .Net HTTP client that allows you to call web service API methods using annotated interfaces or controllers without boilerplate code.

Programming Languages

C#
18002 projects
Liquid
124 projects

Projects that are alternatives of or similar to NClient

restofus
Restofus - a cross-platform (REST) API client.
Stars: ✭ 18 (-28%)
Mutual labels:  http-client, api-client, rest-client
RESTEasy
REST API calls made easier
Stars: ✭ 12 (-52%)
Mutual labels:  http-client, api-client, rest-client
Taviloglu.Wrike.ApiClient
.NET Client for Wrike API
Stars: ✭ 24 (-4%)
Mutual labels:  http-client, api-client, rest-client
SimpleSocial
A simple social network web application using ASP.NET Core 3.1
Stars: ✭ 16 (-36%)
Mutual labels:  asp-net-core, asp-net
squidex-identity
Identity Server for Squidex Headless CMS
Stars: ✭ 28 (+12%)
Mutual labels:  asp-net-core, asp-net
DNZ.SEOChecker
SEO Checker and Recommander Plugin (like wordpress Yoast) for ASP.NET Core.
Stars: ✭ 18 (-28%)
Mutual labels:  asp-net-core, asp-net
Rester
A REST client for almost any web service (Firefox and Chrome Extension)
Stars: ✭ 192 (+668%)
Mutual labels:  http-client, rest-client
FSharp.JsonApi
Use F# to create and consume flexible, strongly typed web APIs following the JSON:API specification
Stars: ✭ 20 (-20%)
Mutual labels:  web-api, asp-net-core
squidex-samples
Samples for Squidex
Stars: ✭ 47 (+88%)
Mutual labels:  asp-net-core, asp-net
I18N
I18N Library for .NET, and Delphi
Stars: ✭ 48 (+92%)
Mutual labels:  asp-net-core, asp-net
YuiAPI
一个浏览器API测试客户端,API文档生成器,支持chrome/firefox/新版edge
Stars: ✭ 25 (+0%)
Mutual labels:  api-client, rest-client
Home
Home for Blazor Extensions
Stars: ✭ 51 (+104%)
Mutual labels:  asp-net-core, asp-net
Rump
REST client for Java that allows for easy configuration and default values. Allows for quick request construction and a huge range of modifications by using response/request interceptors, adjusting default values related to HTTP requests and creating custom instances for when you need multiple API connection setups.
Stars: ✭ 55 (+120%)
Mutual labels:  http-client, rest-client
PersianDataAnnotations
PersianDataAnnotations is ASP.NET Core MVC & ASP.NET MVC Custom Localization DataAnnotations (Localized MVC Errors) for Persian(Farsi) language - فارسی سازی خطاهای اعتبارسنجی توکار ام.وی.سی. و کور.ام.وی.سی. برای نمایش اعتبار سنجی سمت کلاینت
Stars: ✭ 38 (+52%)
Mutual labels:  asp-net-core, asp-net
Httpie
As easy as /aitch-tee-tee-pie/ 🥧 Modern, user-friendly command-line HTTP client for the API era. JSON support, colors, sessions, downloads, plugins & more. https://twitter.com/httpie
Stars: ✭ 53,052 (+212108%)
Mutual labels:  http-client, api-client
unity-simple-http
A dead simple HTTP client for Unity3D
Stars: ✭ 32 (+28%)
Mutual labels:  http-client, rest-client
drowsy
😪 Lazy integrations tool for RESTful interfaces to aid POC development and streamline integrations
Stars: ✭ 19 (-24%)
Mutual labels:  api-client, rest-client
adminlte-aspnetcore2-version
Asp.Net Example version of famous and beautiful AdminLTE control panel themes and template.
Stars: ✭ 64 (+156%)
Mutual labels:  asp-net-core, asp-net
Proxy
The type-safe REST library for .NET Standard 2.0 (NetCoreStack Flying Proxy)
Stars: ✭ 40 (+60%)
Mutual labels:  http-client, rest-client
Crest
HTTP and REST client for Crystal
Stars: ✭ 174 (+596%)
Mutual labels:  http-client, rest-client

logoNClient: automatic type-safe .NET HTTP client

Nuget Nuget (with prereleases) Nuget GitHub last commit GitHub Workflow Status Documentation GitHub
Maintainability Rating Reliability Rating Security Rating Vulnerabilities Coverage

NClient is an automatic type-safe .NET HTTP client that can call web API methods using annotated interfaces. The main difference between NClient and its analogues is that NClient lets you annotate ASP.NET controllers via interfaces and then use these interfaces to create clients. It allows you to get rid of unwanted dependencies on a client side and to reuse an API description in clients without boilerplate code.

// WebService.dll:
public class WeatherController : ControllerBase, IWeatherFacade {
    public Task<Weather> GetAsync(string city, DateTime date) => ...;
}

// WebService.Facade.dll:
[HttpFacade, Path("api/[facade]")] 
public interface IWeatherFacade {
    [GetMethod("{city}")] 
    Task<Weather> GetAsync([RouteParam] string city, [QueryParam] DateTime date);
}

// Client.dll:
IWeatherFacade weatherFacade = NClientGallery.Clients.GetRest()
    .For<IWeatherFacade>(host: "http://localhost:5000")
    .WithSafeResilience(maxRetries: 3)
    .Build();
Weather todaysWeather = await weatherFacade.GetAsync(city: "Chelyabinsk", date: DateTime.Today);

Give us a star

Do you like it? Support the development of this project and star this repo!

🚀 Why use NClient?

Creating clients for web services can be quite a challenge because, in addition to data transfer, you need to implement query building, serialization, retry policy, mapping, error handling, logging — and this is not to mention the maintenance that comes with each update of your APIs. What if you could create clients with a fraction of the effort? This is exactly what NClient hopes to achieve by allowing you to create clients declaratively.

By the way, you can contribute to the NClient, not just use it 😃

💪 Advantages of NClient

  • Integration with ASP.NET: clients are available for all controllers out of the box.
  • Generation of interfaces: interfaces and DTO's are generated by the OpenAPI (Swagger) specification.
  • Resilience: resilience is provided by different strategies. There is Polly support.
  • Serialization selection: various serializers are avaliable for use: System.Text.Json, Newtonsoft JSON, System.XML, MessagePack, Protobuf, your own.
  • Auto validation of responses: preset or custom validation of responses can be set.
  • Auto mapping of responses: native or your own models can be returned from the client instead of responses or DTO.
  • Extension using handlers: handlers allow to add custom logic to the client parts
  • Extension using providers: the client functionality can be extended with native or your own providers.
  • Easy error analysis: your logger can be used in clients, and certainly exceptions have all the required information to investigate.
  • Easy to use with DI: extension methods allow to add a client to a collection of services easily.
  • Maximum flexibility: any step of the request execution pipeline can be replaced with your own.
  • [WIP] All types of applications: the library can be used on backend (ASP.NET) and frontend (Blazor), its planed tо support mobile/desktop (MAUI).
  • [WIP] Various protocols: REST protocol is provided as a ready-made solution, its planed to add GraphQL and RPC.

Features: Dynamic templated routing; Static routing; Dynamic query parameters; Collections as query parameters; Dynamic headers; Static headers; Dynamic body; Auto serialization and deserialization; HTTP/Transport context; Authentication; Asynchronous requests; Timeouts; Cancellation requests; Resilience policy; Response validation; Response mapping; File upload/download; Generic interfaces; Interface inheritance; Client factory; Versioning; Handling; Structured logging, Dependency injection support.

📖 Table of Contents

🏁 How to install?

The easiest way is to install NClient package using Nuget:

dotnet add package NClient

🚧 Requirements

Use of the NClient library requires .NET Standard 2.0 or higher. The NClient controllers can be used with ASP.NET Core and .NET Core 3.1 target or higher.

👩🏼‍💻 How to use?

First you have to create an interface describing available endpoints and input/output data of a service via annotations. After that, you can select the required type of client in NClientGallery and then set additional settings for it if it`s necessary.

Usage with third-party service

If you want to send requests to a third-party service, you should create an interface that describes the service you want to make requests to. Follow the steps below:

Step 1: Install NClient in the client project

dotnet add package NClient

Step 2: Install dotnet-nclient tool

dotnet tool install --global dotnet-nclient

Step 3: Generate the interface describing the API of the web service

dotnet nclient generate facade --api path/to/product-service-swagger.json --output MyProject/Client.cs

This command will generate an interface for the API using the OpenAPI (Swagger) specification:

[Path("api")]
public interface IProductServiceClient
{
    [PostMethod("products")]
    Task<Product> CreateAsync(Product product);
    
    [GetMethod("products/{id}")]
    Task<Product> GetAsync([RouteParam] int id);
}

If necessary, the interface can be changed. It is easy to do this because interface annotation is very similar to the annotation of controllers in ASP.NET. The PathAttribute defines the base path for all interface methods. The PostMethodAttribute specifies the type of HTTP method and the path to endpoint. Moreover, implicit annotations work as in ASP.NET controllers, for example, the BodyParamAttribute attribute will be implicitly set to the product parameter in CreateAsync method. And certainly the route templates are also supported. Read about all the features in the Annotation and Routing sections.

Step 4: Create the client

IProductServiceClient client = NClientGallery.Clients.GetRest()
    .For<IProductServiceClient>(host: "http://localhost:8080")
    .Build();

The GetRest method creates a REST client with System.Text.Json serialization and without resilience policy.

Step 5 (optional): Configure the client

IProductServiceClient client = NClientGallery.Clients.GetRest()
    .For<IProductServiceClient>(host: "http://localhost:8080")
    .WithNewtonsoftJsonSerialization()
    .WithResilience(x => x
        .ForMethod(client => (Func<Product, Task<Product>>) client.CreateAsync)
        .Use(maxRetries: 2, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))))
    ...
    .Build();

After calling the For method, you can configure the client as you need, for example, you can replace the serializer with Newtonsoft.Json, add the retry policy and so on (see full documentation).

Step 6: Send an http request

// Equivalent to the following request: 
// curl -X POST -H "Content-type: application/json" --data "{ id: 1 }" http://localhost:8080/api/products
Product product = await client.CreateAsync(new Product(name: "MyProduct"));

Usage with ASP.NET Core

If you want to generate a client for your ASP.NET web service, you need to extract an interface for your controller and annotate it with NClient attributes. They are very similar to attributes for ASP.NET controllers. Follow the steps below:

Step 1: Install NClient.AspNetCore package on server-side

dotnet add package NClient.AspNetCore

Step 2: Create the controller

public class WeatherForecastController : ControllerBase
{
    public async Task<WeatherForecast> GetAsync(DateTime date) =>
        new WeatherForecast(date: date, temperatureC: -25);
}

Don't annotate your controller with ASP.NET attributes that may semantically conflict with the NClient attributes you are going to use. Other attributes (including your own) can be used without restrictions.

Step 3: Extract the interface for your controller and annotate it with NClient attributes

[HttpFacade, Path("[controller]")]                                // equivalent to [ApiController, Route("[controller]")]
public interface IWeatherForecastController
{
    [GetMethod]                                                   // equivalent to [HttpGet]
    Task<WeatherForecast> GetAsync([QueryParam] DateTime date);   // equivalent to [FromQuery]
}

public class WeatherForecastController : ControllerBase, IWeatherForecastController { ... }

The annotation in the interface instead of the controller allows you to put the interface in a separate assembly. Therefore, the client useing this interface doesn`t depend on the ASP.NET application.

Step 4 (optional): Create the interface for the client

public interface IWeatherForecastClient : IWeatherForecastController { }

You should do it if you want your client type not to contain "Сontroller" in the name or if you want to override some methods for the client (see OverrideAttribute in Annotation section). There is no need to duplicate interface attributes, they are inherited.

Step 5: Add NClient controllers to ServiceCollection in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddNClientControllers();
}

The AddNClientControllers method can be used in combination with the AddControllers. This will allow you to use standard ASP.NET controllers together with NClient controllers in the same application.

Step 6: Install NClient package on client-side

dotnet add package NClient

Step 7: Create the client

IWeatherForecastController client = NClientGallery.Clients.GetRest()
    .For<IWeatherForecastController>(host: "http://localhost:8080")
    .Build();

If you decide to follow the 4th step, use the IWeatherForecastClient interface instead of IWeatherForecastController.

Step 8: Send an http request

// Equivalent to the following request: 
// curl -X GET -H "Content-type: application/json" http://localhost:8080/WeatherForecast?date=2021-03-13T00:15Z
WeatherForecast forecast = await client.GetAsync(DateTime.Now);

🗄 Documentation

You can find NClient documentation on the Wiki.

👩🏼‍🏫 Samples of applications

See samples of applications in the NClient.Samples project.

❤️ Contributing

You’re thinking about contributing to NClient? Great! We love to receive contributions from the community! The simplest contribution is to give this project a star .
Helping with documentation, pull requests, issues, commentary or anything else is also very welcome. Please review our
contribution guide.
It's worth getting in touch with us to discuss changes in case of any questions. We can also give advice on the easiest way to do things.

📦 NuGet Packages

Main

Extensions

Tools

  • dotnet-nclient: The tool for generating interfaces and DTO's by the OpenAPI (Swagger) specification.

Providers

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].