Skip to content

A fluent, strongly-typed HTTP client for .NET 4.5 built on top of the BCL HttpClient.

Notifications You must be signed in to change notification settings

lostdev/Pathoschild.FluentHttpClient

 
 

Repository files navigation

Pathoschild.FluentHttpClient is a fluent wrapper over the .NET 4.5 HttpClient for creating strongly-typed easy-to-use API clients.

Usage

The client is a fluent wrapper over HttpClient. You start by creating a client, and chain methods to configure your request and response.

     IClient client = new Client("http://example.org/api/");

The most common usage is a synchronous HTTP GET, with the response deserialized into a class instance:

     Idea idea = client
        .Get("ideas/14")
        .RetrieveAs<Idea>();

You can fluently customize the request and even directly alter the HttpRequestMessage:

     Idea idea = client
        .Post("ideas", new Idea())
        .WithHeader("Content-Type", "application/json")
        .WithArgument("tenant", "company-name")
        .WithCustom(message =>
        {
           message.Method = HttpMethod.Get;
           message.RequestUri = new Uri("http://example.org/api2/", "ideas");
        })
        .RetrieveAs<Idea>();

The response can also be fluently configured:

     string jsonIdea = client
        .Get("ideas/14")
        .Retrieve()
        .AsString(); // or As<T>, AsList<T>, AsMessage, AsByteArray, AsStream

You also can do everything asynchronously:

     Task<Idea> query = client
        .Get("ideas/14")
        .Retrieve()
        .AsAsync<Idea>();

Reference

The code documentation provides more details on usage: see IClient, IRequestBuilder, and IResponse.

Extending the client

Media type formatters

The client uses the abstract MediaTypeFormatter for serializing and deserializing models for HTTP messages. This is the same type used by the underlying HttpClient and the .NET Web API, so there are many implementations already available. You can also create your own implementation (SerializerMediaTypeFormatterBase might help).

For example, to replace the default DataContractJsonSerializer with the JSON.NET serializer:

     IClient client = new Client("http://example.org/api/");
     client.Formatters.Remove(client.Formatters.JsonFormatter);
     client.Formatters.Add(new JsonNetMediaTypeFormatter());

About

A fluent, strongly-typed HTTP client for .NET 4.5 built on top of the BCL HttpClient.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 100.0%