Whenever I’ve wanted to create a SDK for my WebApi’s I’m surprised by the amount of bolierplate code you end up with. HttpClient made things easier for us, but you still end up wrapping HttpClient and passing generics around.
I wanted something between Simple.Data and angular’s $http service, the main driver was to make my tests as readable as possible. I’ve messed around with .NET 4 dynamic objects before, so I set about creating a dynamic wrapper around HttpClient and a fluent API I could re-use. It’s passed the rule of 3 as I’ve used it for multiple clients. A side note is that it should be trivial to generate DalSoft.RestClient code examples in your WebApi docs.
I know there are a couple of dynamic rest clients out there but I wanted mine to work/look a particular way. The next thing I’m considering is something called “static by example”- this is where you would call a method at the end of your tests and a dll is emitted with a static object that contains all the DalSoft.RestClient dynamic members and methods that were invoked – this dll can then be shipped as your SDK!
Below are some quick examples and an explanation of what you can do with DalSoft.RestClient today, for more documentation and examples head over to the GitHub repo
Install the NuGet package:
PM> Install-Package DalSoft.RestClient
The code below is a live working example that you can copy and paste.
So what is the code above doing?
It’s performing a HTTP GET on http://jsonplaceholder.typicode.com/posts/1. DalSoft.RestClient generates the posts/1
part of the uri by convention using the member access Posts(1), it then looks for the HTTP method at the end of the chain in this case Get().
Get() returns a dynamic deserialized from the response content from http://jsonplaceholder.typicode.com/posts/1. So setting the variable post means that post.id works as expected. For convenience the HttpResponseMessage is attached to the type, meaning you easily check things like the status code (in our case for example post.HttpResponseMessage.StatusCode).
DalSoft.RestClient supports implicit casting, in our example change the type of the post variable to a static type and it magically works as you would expect (it of course uses Json.NET under the hood).
You can also cast the post variable to a HttpResposneMessage too.
And it works with collections too.
Post and Put work in much the same way except you pass an object into the HTTP method, this can be a static object type or an anonymous object.