Follow links
Retrofit works great and probably has the cleanest api as far as rest clients goes in the java world. The one limitation is that it's really hard to use to follow links. I understand that it probably wasn't a design goal but would it be something you'd consider? I could easily call the url directly but I really want to be able to use the error handling, logging, converters and everything else configured in the RestAdapter.
Currently you can do:
@GET("/{path}")
SomeObject get(@EncodedPath("path") String path);
It works well but this means you can only follow links going to the server configured with the RestAdapter. What do you think about adding a Url annotation?
@GET
SomeObject get(@Url String url);
@POST
void post(@Url String url, @Body SomeObject object);
I'd say it's a little unusual to have REST calls where you don't have a path you know ahead of time. Now, your server can change dynamically if you need it, try extending the Server class.
(We provide ChangeableServer for hosts that change at runtime)
There are many different flavors of REST ranging from knowing everything ahead of time to knowing almost nothing (HATEAOS).
While Retrofit's design is obviously not trying to solve for HATEOAS, many API's live in between. ChangeableServer doesn't really help since unless you're following a link, you still want to hit the original server.
I really, really wouldn't like to support this. It compromises Retrofit's greatest asset which is type-safety of explicit endpoints.
I posted a hack for this on G+ last week, though: https://plus.google.com/117349328786944125466/posts/63NCah3BiHb
I don't think a @Url annotation would compromise type-safety. The way I see it @Url endpoint are really like @Path endpoints except you don't know what the url looks like ahead of time. You'd still be able to append query parameters or add a body. You still should know the semantics of the endpoint ahead of time. The only constraint we'd need to enforce is that @Url can't be used with @Path in a single endpoint definition.
Thoughts on my last comment?
The current version of retrofit isnt designed for opaque urls or hypermedia links. It doesnt matter whether the link referred to is on the same host or not. Retrofit is designed for uri templates (eg not hypermedia opaque urls). Personally, I think supporting processing hypermedia links shoul£d be discussed in V2. An api I am working on uses link pagination as does apis like github. Having to parse them works but is clunky.
My preference would be to tack this onto the V2 discussion rather than tacking onto v1. Jake's hack should get you by for now. Keep in mind, I have vested stake in this too, as I'd like to be able to use retrofit for hypermedia apis I work on.
"The way I see it
@Urlendpoint are really like@Pathendpoints except you don't know what the url looks like ahead of time."
You also don't know the request data (body, path params, query params, encoding) or response type and format. At that point you're basically just using Retrofit as an asynchronous HTTP client since you have to supply all the necessary info for the request and the response yourself.
That's true if you're dealing with a "pure" HATEAOS api but there are a lot of hybrid cases where you do know the request data and/or response type.
+1 for this feature request. I would love to have this implemented.
Agreed with @benoitdion, my API design is hybrid as well.
URI template is not part of REST. A RESTful API is a bit like a browser: knowing a bunch of top-level endpoints before hand, and follow the link. One benefit is not repeating the URI template logic on the client side.
+1 for me as well. If Retrofit had more HATEOAS support it would be a one stop shop for me.
Hopefully it will be done gracefully as whole Retrofit.
+1 as well. Doing it via removal of host. But would be nice to have some better support in the library. We use links a lot.
+1 for me too.
I don't mean to "me too" this Closed issue, I just wanted to point out that Google's Blobstore requires a server to request the upload URL for file content. Naturally, my backend returns the URL to the client as @benoitdion supposes in the OP, where I then need to upload my file content to this newly provided URL, which looks something like this:
http://myappengineproject.appspot.com/v1/upload/AMmfu6a_UnifhJWCArFhenZj-ReJtPqCsW54fTy6zPLuV61IWaHpnTUKwDIUmJkqg4AdmAx7DgxRMvko8_J8FQ4o49yv6IpifaKeVdJERSgurmXwI3ty5AsaJvC6zk9MyNAuyA5FTf4q/ALBNUaYAAAAAVKnSCBJqm9jIZKt4cx1AnRxFH-dbq3Lc/
Currently it seems that I'm forced to remove the root of the URL (as it is already the setEndpoint) in order to do something like:
@Multipart
@POST("/{blobpath}/")
void storeImageBlob(@EncodedPath("blobpath") String blobpath, @Part("file") TypedFile image, Callback<String> response);
Also, you'll notice I have to use the EncodedPath annotation instead of Path because the slashes in the Blobstore-returned URL are inappropriately being converted to %2F.
It's just all inconvenient and it doesn't seem like best practice considering that the EncodedPath annotation is deprecated. I just started using this library and I'm new to all this so I was hoping to have clarified the preferred way of using a URL path returned by an API, to make subsequent requests.
But I found solution! First, we make custom Endpoint (I've found it on Stack Overflow ):
public final class UploadEndpoint implements Endpoint {
private String url;
public void setUrl(String url) {
this.url = url;
}
@Override public String getName() {
return "default";
}
@Override public String getUrl() {
if (url == null) throw new IllegalStateException("url not set.");
return url;
}
}
Now, let's look at the URL:
https://example.com.
Yes! We have 2 slashes (/) here.Why not using them?! So, I divided URL into 2 parts: https: with no slashes and all other part (one slash goes to @ PUT("/{path}"), while another goes to String secondPart)
String secondPart = httpadress.substring(httpadress.indexOf("https")+7);
Now, When I make RestAdapter I write:
endpoint = new UploadEndpoint();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(endpoint) //call your base url
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
worker = restAdapter.create(MyApi.class)
And when needed, I write:
endpoint.setUrl("https:");
worker.uploadFile(secondPart,.... something else)
+1
For instance a REST web service returns a pagination object as part of the result with absolute URLs like this:
{
"result": [
{
"id": 101,
"name": "Daniel"
},
{
"id": 102,
"name": "Michael"
},
{
"id": 103,
"name": "Chris"
}
],
"pagination": {
"next": "http://www.foo.com/users?offset=150",
"previous": "http://www.foo.com/users?offset=50"
}
}
I think @benoitdion proposal (@Url) is good. You can make it more strict by saying that the method signature has exactly one parameter (type of string, with @Url) or exactly two (first parameter: type of string, with @Url ; second: Callback).
Uploading images looks not too easy...
public interface ImageService {
@GET("/{url}")
Response download(@Path(value = "url", encode = false) String url);
}
public Bitmap downloadImage(Uri uri) {
Bitmap result = null;
String scheme = uri.getScheme() + ":";
imageEndpoint.setUrl(scheme);
Response response = imageService.download(uri.toString().replaceAll(scheme + "/", ""));
InputStream is = null;
try {
is = new BufferedInputStream(response.getBody().in());
result = BitmapFactory.decodeStream(is, null, null);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if(is != null) {try {is.close();} catch (Exception e) {}}
}
return result;
}
imageEndpoint is same as Kondra007 used.
The solution suggested by @Kondra007 doesn't seem to work with asynchronous calls (where you supply a Callback). I created an OverrideEndpoint that extends Endpoint. I override the base url right before I call my special endpoint, and reset it right after. This doesn't work. The default endpoint is still used for my call.
Most likely this is because the asynchronous calls are queued in an executor and by the time the call to getUrl(..) actually happens, we've already reset the url.
Now, a solution to this problem, could be to only reset the endpoint after the next call to getUrl(..), but this doesn't work either since you don't know that your call is the next one in the queue. There could be many calls not yet executed waiting to go.
At the moment I can't find a workable workaround.
#927 only handles relative urls. It is still inadequate if the url returned is absolute or has a different base url.