I’m a big fan of making idiomatic language bindings for APIs. Making common tasks such as URI generation, transport, authentication, and payload parsing configurable options and providing a higher-level API lets application developers focus on the business domain instead of low-level networking.
.NET developers looking to write API wrappers without starting from
scratch should check out RestSharp from John Sheehan. Similar to Ruby’s HTTParty and others, RestSharp provides a number of features to make writing wrappers for REST web services a snap, including:
- Automatic XML and JSON parsing including Fuzzy element name matching (“product_id” in XML/JSON will match C# property named ‘ProductId’)
- Support for GET, POST, PUT, HEAD, OPTIONS, DELETE
- oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authentication
- Multi-part form/file uploads
- Custom serialization and deserialization via ISerializer and IDeserializer
- Both sync and async requests
Here’s a quick example of making a simple request for XML from an API using Basic Auth:
var client = new RestClient(); client.BaseUrl = "http://twitter.com"; client.Authenticator = new HttpBasicAuthenticator("username", "password"); var request = new RestRequest(); request.Resource = "statuses/friends_timeline.xml"; RestResponse response = client.Execute(request);
In addition to using the built-in Authenticators,
you’re free to create your own:
var client = new RestClient("http://example.com"); client.Authenticator = new SimpleAuthenticator("username", "foo", "password", "bar"); var request = new RestRequest("resource", Method.GET); client.Execute(request);
Perhaps most impressive is RestSharp’s support for a number of environments including .NET 3.5+, Silverlight 4, Windows Phone 7, Mono, and MonoTouch. Be sure and check out the project readme for advanced usage and tips on contributing.