Android consuming api with retrofit library

Posted in Android By Raj On January 7, 2017


When I started learning Android I used to make requests using built-in AsyncTask to get the data from the server’s but with that, we did face lot of problems and it was not that much easy to make parallel requests using AsyncTasks so, after doing some analysis finally we decided to go with Retrofit Library, in this article, I am going to explain how to consume WordPress rest API using Retrofit Library

Retrofit Library

Enable WordPress Rest APIs

I am going to use Jetpack to enable rest APIs for my blog, what you need to do is just go to the settings of jetpack and switch on JSON API and then hit the below URL to get the JSON response


Creating Android Project

In Android Studio click File -> New -> New Project, enter application name is Android Retrofit Library and then fill up all mandatory fields

Open build.gradle file and update with below dependencies

Open anddroidmanifest.xml file and update with below entry to enable network access

Open colors.xml file and update with the below color codes

Generate POJO’s

The jsonschema2pojo tool automatically generate POJOs based on the provided JSON Object or Array’s, if you are familiar with JSON then I would recommend you to use automated tools, otherwise please use manual approach which will help you to get some idea on JSON

The below POJO’s are generated using jsonschema2pojo tool

Building REST client using Retrofit Library

The below posts interface has a method called getPosts() and by calling this method it makes a request to “/posts” rest API by using GET request which is specified above the method as a @GET annotation and returns posts collection

Every method must have an annotation which talks about what kind of request we are going to make, if you want to get specific post information  then you need to pass postID as a parameter to the getPostByID method something like below

The below class is going to be used to instantiate WordPress retrofit client in the MainActivity class

Display WordPress posts

The activity_main.xml file contains listview collection which will be used to display display posts collection

The activiy_post.xml file contains three fields ImageView which display post thumbnail, title field shows post title and content filed shows post excerpt

Oncreate method of main activity class we are going to get retrofit client instance by calling WordPressClient.getClient(), By making a callback request get the response of getPosts() method

Use PostsAdapter to bind posts information to the view

Finally, run the app and it should display list of posts which are published in WordPress blog