Tran Triet Tran Triet - 1 month ago 5
reST (reStructuredText) Question

In Retrofit, why use one method per interface

I am new to android and REST client. I am using retrofit to build an app to communicate with an API.

Many tutorials said the best practice is to declare 1 method per interface (so many methods means many interfaces).

Examples: if I want 2 method, a GET and a POST. I will need two interfaces:

public interface GetService {
@GET("/abc/xyz")
Call <ABC> getService();
}

public interface PostService {
@POST("/abc/def")
Call<XYZ> postServer(@Body XYZ content);
}


and in the main_activity I will need to call

//call get
GetService get = ServiceGenerator.createService(GetService.class);
ABC call1 = get.getService();
//call post
PostService post = ServiceGenerator.createService(PostService.class);
XYZ call2 = post.postService();


Why can't I have only one interface like this:

public interface APIInterface {
@GET("/abc/xyz")
Call <ABC> getService();

@POST("/abc/def")
Call<XYZ> postServer(@Body XYZ content);
}


and in the Main_Activity, I only need to do the following:

APIInterface api = ServiceGenerator.createService(APIInterface.class);
ABC call1 = api.getService();
XYZ call2 = api.postServer();

Answer

You don't have to follow this "good practice" with one service per interface. If you use one interface per business part like below, it's ok.

public interface ProductRestService {
    @GET("/product/****")
    Call <Product> getProduct(long id);

    @PUT("/product/****")
    Call <Product> update(long id, @Body Product product);

    @POST("/product/****")
    Call <Product> create(@Body Product product);

    @DELETE("/product/****")
    Call <Void> deleteProduct(long id);
}

The goal is just to avoid an interface with all your app's services