How to use GraphQL with Retrofit on Android?

2019-04-28 06:34发布

问题:

I'm new to GraphQL but I have been using Retrofit for a while now and its easy to use and fast. GraphQL is much different than rest apis in terms of how you pass data. There really are not too many tutorials out there on using GraphQL with Android, I was only able to find this video (https://www.youtube.com/watch?v=P0uJHI7GjIc&t=1s) but there is no real code in there.

In my current code for retrofit calls I have an endpoint I set like so:

final RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(endPoint)
                .build();
        T service = restAdapter.create(clazz);

Then I call a rest service like this:

@GET("/users/{login}")
    Observable<Github> getUser(@Path("login") String login);

Now with GraphQL you only have a base url and no service path. Also if you are querying like userId=1 then you have to send as Post with Body parameters:

operationName: arbitrary name ,
query: "{users(userid:$userId){username}}, 
variables: "{"userId":1}"

I'm just not sure how this translates to Retrofit

回答1:

Building Queries & Parsing responses for GraphQL is not straightforward. If you are using this on pet-projects, i recommend to start exploring Apollo. This client is under serious development but you can already have a look and play with it.

https://github.com/apollographql/apollo-android

I enjoyed working with Apollo so far, and there are nice features on their roadmap: RxJava Integration, Retrofit, Subscriptions and support for AutoValue