Pathoschild.FluentHttpClient is a fluent wrapper over the .NET 4.5 HttpClient for creating strongly-typed easy-to-use API clients.
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>();
The code documentation provides more details on usage: see IClient
, IRequestBuilder
, and IResponse
.
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());