开发者

How do you use Restful APIs?

开发者 https://www.devze.com 2023-01-23 12:13 出处:网络
When you are using another web applications Restful API, do you usually use a wrapper library or开发者_开发知识库 do you use the Restful API directly with a HTTP client?This is a hard question to answ

When you are using another web applications Restful API, do you usually use a wrapper library or开发者_开发知识库 do you use the Restful API directly with a HTTP client?


This is a hard question to answer, primarily because in the current state of the industry, the right answer is very impractical.

The correct answer, in my opinion, is you should not use a wrapper API. The uniform interface is HTTP and that should be the programming model the client works against.

Having said that, there is nothing wrong with having helper classes that parse media types to generate strongly typed versions. Something like this,

var response = HttpClient.Get(linkTofoo);
if (response.ContentType =='application/foo') {
   var strongFoo = FooHelper.Parse(fooResponse);
   HandleFoo(strongFoo);
}

Unfortunately, a vast majority of apis that claim to be RESTful, are not. They do not respect the self-description and hypermedia constraints and therefore they make it very difficult to interact with them in a RESTful way. They require you to do client side URI construction and have prior knowledge of the types that will be returned from endpoints.

The sad fact is that with many APIs you have little choice but to use a provided client proxy library. This should not be the case.

If you are looking for evaluating a client library, just make sure it is a stateless one. The client library should not start managing the lifetimes of the returned objects. Http caching does that, so unless it is an uber-smart library that can invalidate object references when the cached representation expires, avoid any stateful client libraries.

e.g.

var foo = remotelibrary.GetFoo(233);
var bar = foo.bar; // If this causes an HTTP request
var barcopy2 = foo.bar // and this doesn't because it already has a reference to bar 
                       // I would be very leary of using this library


It is almost certainly going to be better in the long run to use a library. This allows you to abstract away the restful-ness of the design and ignore the whole HTTP business.

If there is not an existing library for whatever API you're using then you should consider writing your own.

0

精彩评论

暂无评论...
验证码 换一张
取 消