Awesome Open Source
Awesome Open Source

diagram

.NET REST Client Framework for all platforms

The best .NET REST API Client with task-based async, strong types, and dependency injection on all platforms. Consume your ASP .NET Core Web APIs or consume RESTful APIs over the internet in C#, F#, or Visual Basic. It's designed for functional-style programming with F# in mind.

NuGet: RestClient.Net

Follow Me on Twitter for Updates

.NET

5.0 Release

5.0 brings a Fluent API, immutable types, lots of useful extension methods, and thorough unit testing. Check out the tests for code examples.

Follow Me on Twitter for Updates

Why You Should Use It

  • Treats Urls as first-class citizens with Urls. URLs are immutable records and have a fluent API for construction.
  • Designed for Dependency Injection. Mock your REST calls and add RestClient.Net to your IoC container with one line of code
  • Async friendly. All operations use async, await keywords
  • Automatic request/response body serialization to/from strong types (JSON, Binary, SOAP, Google Protocol Buffers)
    • The library is decoupled from Newtsonsoft so that you can use any serialization method or version of Newtonsoft. This means that you can use it with any version of Azure Functions.
  • Install from NuGet on any platform from .NET Framework 4.5 up to .NET 5. Supports Xamarin (Mono, iOS, Android), UWP, WebAssembly and Unity with .NET Standard 2.0
  • Supports GET, POST, PUT, PATCH, DELETE with ability and custom methods
  • Tight code and complete test coverage means you can make a change if you need to diagram
  • Fluent API for construction, non-destructive mutation, and Url construction
  • Uses .NET Core Logging - ILogger to allow logging of all aspects of HTTP calls

Examples

For a complete set of examples, see these unit tests.

POST an Object and get Response

using var client =
    //Build the Url from the host name
    new Client("jsonplaceholder.typicode.com".ToHttpsUriFromHost());

UserPost userPost = await client.PostAsync<UserPost, UserPost>(
    //POST the UserPost to the server
    new UserPost { title = "Title" }, "posts"
    );

Dependency Injection (RestClient.Net.DependencyInjection NuGet Package)

Wiring it up

var serviceCollection = new ServiceCollection()
    //Add a service which has an IClient dependency
    .AddSingleton<IGetString, GetString1>()
    //Add RestClient.Net with a default Base Url of http://www.test.com
    .AddRestClient((o) => o.BaseUrl = "http://www.test.com".ToAbsoluteUrl());

//Use HttpClient dependency injection
_ = serviceCollection.AddHttpClient();

Getting a Global IClient in a Service

public class GetString1 : IGetString
{
    public IClient Client { get; }

    public GetString1(IClient client) => Client = client;

    public async Task<string> GetStringAsync() => await Client.GetAsync<string>();
}

Getting a IClient Using a Factory

public class GetString2 : IGetString
{
    public IClient Client { get; }

    public GetString2(CreateClient createClient)
    {
        //Use the options to set the BaseUrl or other properties on the Client
        Client = createClient("test", (o) => { o.BaseUrl = o.BaseUrl with { Host = "www.test.com" }; });
    }

    public async Task<string> GetStringAsync() => await Client.GetAsync<string>();
}

Make Call and Construct Client

//This constructs an AbsoluteUrl from the string, makes the GET call, and deserializes the JSON to a strongly typed list
//The response also contains a Client with the base of the Url that you can reuse
//Note: not available on .NET 4.5

var response = await "https://restcountries.eu/rest/v2"
    .ToAbsoluteUrl()
    .GetAsync<List<RestCountry>>();

Query Github Issues with GraphQL (You must authorize GraphQL Github App)

using RestClient.Net.Abstractions.Extensions;
using System.Collections.Generic;
using System.Threading.Tasks;
using Urls;

namespace RestClient.Net
{
    public static class GitHubGraphQLMethods
    {
        public static async Task<T> GetIssues<T>(string repo, string accessToken)
        => (await "https://api.github.com/graphql"
            .ToAbsoluteUrl()
            .PostAsync<QueryResponse<T>, QueryRequest>(
                new QueryRequest("{ search(query: \"repo:" + repo + "\", type: ISSUE, first: 100) {nodes {... on Issue { number title body } } }}")
                , HeadersExtensions.FromBearerToken(accessToken)
            .Append("User-Agent", "RestClient.Net"))).Response.Body.data.search;
    }

    public record QueryRequest(string query);
    public record Issue(int? number, string title, string body);
    public record Issues(List<Issue> nodes);
    public record Data<T>(T search);
    public record QueryResponse<T>(Data<T> data);

}

Url Construction with F#

[<TestMethod>]
member this.TestComposition () =

    let uri =
        "host.com".ToHttpUrlFromHost(5000)
        .AddQueryParameter("fieldname1", "field<>Value1")
        .WithCredentials("username", "password")
        .AddQueryParameter("FieldName2", "field<>Value2")
        .WithFragment("frag")
        .WithPath("pathpart1", "pathpart2")

    Assert.AreEqual("http://username:[email protected]:5000/pathpart1/pathpart2?fieldname1=field%3C%3EValue1&FieldName2=field%3C%3EValue2#frag",uri.ToString());

Donate

Coin Address
Bitcoin 33LrG1p81kdzNUHoCnsYGj6EHRprTKWu3U
Ethereum 0x7ba0ea9975ac0efb5319886a287dcf5eecd3038e

Contribution


Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
C Sharp (272,064
Android (40,813
Ios (19,240
Json (11,109
Rest (4,060
Xml (3,777
Async (3,143
Xamarin (1,752
Uwp (983
Protocol Buffers (690
Rest Client (573
Netstandard20 (242
Related Projects