Creating REST end points - addam01/android-rx-retro-kickstart GitHub Wiki
Creating REST end points
Overview
In this tutorial, we'll run through on creating a REST end point with the models, REST API, Retrofit, and RxJava.
If you haven't gone through the creating activity tutorial, here is the link
The API end point
-
First off, identify your REST API end point URL, the request data, and response data.
-
Create the POJO for the request and response GSON annotation class for your JSON API handling in your Model package. You'll have to create 2 different classes, one for the Request and other for Response.
-
Here is an example of a login request:
public class SampleRequest { @SerializedName("username") private String name; @SerializedName("password") private String password; public SampleRequest(String name, String password) { this.name = name; this.password = password; }}
-
Here is an example of a login response
public class SampleResponse { @SerializedName("status") private Boolean status; @SerializedName("token") private String token; public SampleRequest(String name, String password) { this.name = name; this.password = password; }}
-
In the Core -> Rest package, create an interface Service class for your API. Here is an example
public interface RestServices { @POST("some request end") Observable<SampleResponse> ResquestSample(@Body SampleRequest sampleRequest);}
The observable must have a type restricted to the Response of the API.
-
Create the service Object in the Core -> Rest -> RestRepository.java if you havent done so yet.
-
Declare an Observer in the Core -> Rest ->APIs like so
Observable<SampleResponse> getSampleResponse(String username, String password);
You'll need to pass the parameters of the Request constructor here.
-
In the RestRepository.java, you'll implement the declaration automatically. Just change the return to return your Service Object in the method. Example:
public Observable<SampleResponse> getSampleResponse(String username, String password) { return mRestServices.ResquestSample(new SampleRequest(username,password)); }
The mRestService is the object you create that contains the method calling for the URL end point
-
Now back to your package's retroRest, create a binder class for your API calling execution. This will be where your presenter class calls to run the threading. Like so
public class GetSample implements RetrofitExecutable { private String name; private String password; private APIs mAPIs; public GetSample(APIs APIs) { mAPIs = APIs; } public void setSample(String name, String password){ this.name = name; this.password = password; } @Override public Subscription execute(Subscriber subscriber) { return mAPIs.getSampleResponse(name,password) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } }
In the next tutorial, we'll talk about how to call the thread REST end points