• Stars
    star
    366
  • Rank 116,547 (Top 3 %)
  • Language
    C#
  • License
    MIT License
  • Created about 6 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET REST Client Framework for all platforms

diagram

.NET REST Client Framework for all platforms

buildandtest

RestClient.Net is a powerful .NET REST API client that features task-based async, strong types, and dependency injection support for all platforms. Use it to consume ASP.NET Core Web APIs or interact with RESTful APIs over the internet in C#, F#, or Visual Basic. It's designed with functional-style programming and F# in mind.

NuGet: RestClient.Net

Follow Me on Twitter for Updates

.NET

6.0 Release

This release updates all dependencies and targets major versions of .NET: 4.5, 5, 6, and 7.

Follow Me on Twitter for Updates

Key Features

  • First-class URLs: Utilizes Urls to treat URLs as immutable records with a fluent API for construction.
  • Dependency Injection Support: Easily mock REST calls and add RestClient.Net to your IoC container with a single line of code.
  • Async-Friendly: All operations use async and await keywords.
  • Automatic Serialization: Automatically serializes request/response bodies to/from strong types (JSON, Binary, SOAP, Google Protocol Buffers). The library is decoupled from Newtonsoft, allowing you to use any serialization method or version of Newtonsoft. This means compatibility with any version of Azure Functions.
  • Cross-Platform Compatibility: 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.
  • HTTP Methods: Supports GET, POST, PUT, PATCH, DELETE, and custom methods.
  • Fluent API: Provides a fluent API for construction, non-destructive mutation, and URL construction.
  • Logging: Uses .NET Core Logging - ILogger for logging all aspects of HTTP calls.
  • Thread Safety: Immutable client for thread safety.
  • High-Quality Code: Tight code and complete test coverage allow you to make changes if needed.

diagram

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

Contribution

More Repositories

1

Device.Net

A C# cross platform connected device framework
C#
616
star
2

ioc_container

A lightweight, flexible, and high-performance dependency injection and service location library for Dart and Flutter
Dart
60
star
3

Trezor.Net

Cross platform C# library for talking to the Trezor hardwarewallet
C#
43
star
4

Jayse

Lossless conversion of JSON to and from statically-typed, immutable objects in Dart and .NET
Dart
29
star
5

CryptoCurrency.Net

CryptoCurrency.Net
C#
19
star
6

Samples

C#
19
star
7

Urls

Treat Urls as first-class citizens
C#
19
star
8

Ledger.Net

Cross Platform C# Library For Ledger Hardware Wallet
C#
15
star
9

flutter_ioc_container

A lightweight, flexible, and high-performance dependency injection and service location library for Flutter
C++
13
star
10

firestore_fakes

Fake Firestore Data With Control
Dart
12
star
11

austerity

Dart and Flutter static code analysis, but not for the faint hearted
Dart
9
star
12

papilio_note

Markdown notes anywhere
Dart
8
star
13

COVID-19-DB

COVID-19 database generated from Johns Hopkins CSSE data
C#
8
star
14

navigation_drawer_menu

Flutter Material Design Navigation Drawer Menu
Dart
8
star
15

json_to_dto

Convert JSON to Dart DTOs and back. Automate the model creation and the toJson and fromJson methods
C++
7
star
16

listenable_future_builder

A general purpose Flutter Builder widget that allows you to do async work on controller initialization
Dart
7
star
17

papilio

Build beautiful apps with Flutter
Dart
7
star
18

flutter_location_wakeup

Listens for significant location changes on the device and wakes it up when they arrive
Dart
6
star
19

Hardwarewallets.Net

C# Hardwarewallets
C#
6
star
20

KeepKey.Net

Cross Platform KeepKey Hardware Wallet C# Library
C#
6
star
21

arborio

An elegant, flexible Treeview with Animation. Display hierarchical data in Flutter.
Dart
6
star
22

fixed_collections

Dart collections that you can't modify
Dart
5
star
23

DatabaseLogging

C#
5
star
24

bloobit

Flutter state management, as simple as it gets
C++
5
star
25

Moqesq

C#
4
star
26

notifier_builder

A Builder for Flutter Notifiers
C++
4
star
27

flutter_test_extensions

Dart
3
star
28

fhir_client

Dart/Flutter library for consuming FHIR server APIs. Simple, stateless http extensions that make it easy to consume FHIR
Dart
3
star
29

nadz

Carefully crafted monads, such as Result and Option for exhaustive pattern matching in Dart.
Dart
2
star
30

papilio_bloc

Bloc, but in a different flavor
Dart
2
star
31

AsyncDictionary

C#
2
star
32

benchmarks

I benchmark things and then tell everybody about it
Dart
2
star
33

Cashper

C#
1
star
34

Hardfolio

Hardfolio
1
star
35

AutomatedTesting

A Windows automated testing framework
C#
1
star
36

DBTogRPC

C#
1
star
37

call_and_response

C++
1
star
38

Voom

ViewModels, made easy
C#
1
star
39

fake_httpclient

Fake HTTP calls in Widget Tests without abstractions
Dart
1
star