1. Code
  2. Coding Fundamentals
  3. Rest API

Android From Scratch: Using REST APIs

In this tutorial, I'm going to show you how to use the classes and methods available in the Android SDK to connect to remote web servers and interact with them using their REST endpoints. I'll also show you how to conserve bandwidth using caching.
Scroll to top
This post is part of a series called Android From Scratch.
Android From Scratch: Hardware Sensors

Most of us have developed voracious appetites for new information, what with the Internet being such an important part of our lives. Our attention spans too are shorter than ever, so building Android applications whose content is static can be a bad idea. Instead, you should consider building applications that can display fresh content every time the user opens them. 

That might sound hard, but with more and more websites exposing their resources through REST APIs, it's actually quite easy. (See our Beginner’s Guide to HTTP and REST for a primer.)

In this tutorial, I'm going to show you how to use the classes and methods available in the Android SDK to connect to remote web servers and interact with them using their REST APIs.

1. Enabling Internet Access

Making use of a REST API obviously involves using the Internet. However, Android applications can access the Internet only if they have the android.permission.INTERNET permission. Therefore, before you start writing any networking code, you must make sure that the following uses-permission tag is present in your project's manifest file:

1
<uses-permission android:name="android.permission.INTERNET" />

Because android.permission.INTERNET is not considered a dangerous permission, you don't have to request for it during runtime on devices running API Level 23 or higher.

2. Creating Background Threads

The Android platform does not allow you to run network operations on the main thread of the application. Therefore, all your networking code must belong to a background thread. An AsyncTask subclass has the following methods for performing work off the main thread:

  • onPreExecute(): This method runs on the UI thread, and is used for setting up your task (like showing a progress bar).
  • doInBackground(): This is where you implement the code to execute the work that is to be performed on the separate thread.
  • onProgressUpdate(): This is invoked on the UI thread and used for updating progress in the UI (such as filling up a progress bar).
  • onPostExecute(): Again on the UI thread, this is used for updating the results to the UI once the AsyncTask has finished loading.
1
private class MyTask extends AsyncTask<Void, Void, Void> { 
2
    
3
    
4
     // All your networking logic

5
        // should be here

6
    
7
    
8
    }

If you want to learn more about running operations in background threads, I suggest you read this tutorial about background operations from the Android From Scratch series.

3. Creating an HTTP Connection

By using the openConnection() method of the URL class, you can quickly set up a connection to any REST endpoint. The return value of openConnection() must be cast to an instance of either HttpURLConnection or HttpsURLConnection, depending on whether the endpoint is accessed over HTTP or HTTPS. Both HttpURLConnection and HttpsURLConnection allow you to perform operations such as adding request headers and reading responses.

The following code snippet shows you how to set up a connection with the GitHub API's root endpoint:

1
// Create URL

2
URL githubEndpoint = new URL("https://api.github.com/");
3
 
4
// Create connection

5
HttpsURLConnection myConnection =
6
        (HttpsURLConnection) githubEndpoint.openConnection();

Note that HttpsURLConnection is a subclass of the HttpURLConnection class.

4. Adding Request Headers

Most websites that offer REST APIs want to be able to identify your app uniquely. The easiest way to help them do so is to include a unique User-Agent header in all your requests.

To add a User-Agent header to your request, you must use the setRequestProperty() method of the HttpURLConnection object. For example, here's how you set the User-Agent header to my-rest-app-v0.1:

1
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.1");

You can add multiple headers to your request by calling the setRequestProperty() method multiple times. For example, the following code snippet adds an Accept header and a custom Contact-Me header:

1
myConnection.setRequestProperty("Accept", 
2
        "application/vnd.github.v3+json");
3
myConnection.setRequestProperty("Contact-Me", 
4
        "hathibelagal@example.com");

5. Reading Responses

Once you have passed all the request headers, you can check if you have a valid response using the getResponseCode() method of the HttpURLConnection object.

1
if (myConnection.getResponseCode() == 200) {
2
    // Success

3
    // Further processing here

4
} else {
5
    // Error handling code goes here

6
}

If the HttpURLConnection class gets a redirect response code, such as 301, it handles it automatically and follows the redirect. Therefore, usually, you will not have to write any extra code to check for redirects.

If you get no errors, you can now call the getInputStream() method to get a reference to the input stream of the connection.

1
InputStream responseBody = myConnection.getInputStream();

Most REST APIs these days return data formatted as valid JSON documents. Therefore, instead of reading from the InputStream object directly, I suggest you create an InputStreamReader for it.

1
InputStreamReader responseBodyReader = 
2
        new InputStreamReader(responseBody, "UTF-8");

6. Parsing JSON Responses

The Android SDK has a class called JsonReader, which makes it very easy for you to parse JSON documents. You can create a new instance of the JsonReader class by passing the InputStreamReader object to its constructor.

1
JsonReader jsonReader = new JsonReader(responseBodyReader);

How you extract a specific piece of information from the JSON document depends on its structure. For example, the JSON document returned by the root endpoint of GitHub's REST API looks like this:

1
{

2
  "current_user_url": "https://api.github.com/user",

3
  "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}",

4
  "authorizations_url": "https://api.github.com/authorizations",

5
  "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}",

6
  "emails_url": "https://api.github.com/user/emails",

7
  "emojis_url": "https://api.github.com/emojis",

8
  "events_url": "https://api.github.com/events",

9
  "feeds_url": "https://api.github.com/feeds",

10
  "followers_url": "https://api.github.com/user/followers",

11
  "following_url": "https://api.github.com/user/following{/target}",

12
  "gists_url": "https://api.github.com/gists{/gist_id}",

13
  "hub_url": "https://api.github.com/hub",

14
  "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}",

15
  "issues_url": "https://api.github.com/issues",

16
  "keys_url": "https://api.github.com/user/keys",

17
  "notifications_url": "https://api.github.com/notifications",

18
  "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}",

19
  "organization_url": "https://api.github.com/orgs/{org}",

20
  "public_gists_url": "https://api.github.com/gists/public",

21
  "rate_limit_url": "https://api.github.com/rate_limit",

22
  "repository_url": "https://api.github.com/repos/{owner}/{repo}",

23
  "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}",

24
  "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}",

25
  "starred_url": "https://api.github.com/user/starred{/owner}{/repo}",

26
  "starred_gists_url": "https://api.github.com/gists/starred",

27
  "team_url": "https://api.github.com/teams",

28
  "user_url": "https://api.github.com/users/{user}",

29
  "user_organizations_url": "https://api.github.com/user/orgs",

30
  "user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}",

31
  "user_search_url": "https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"

32
}

As you can see, the response is just one large JSON object that contains several keys. To extract the value of the key called organization_url from it, you will have to write the following code:

1
jsonReader.beginObject(); // Start processing the JSON object

2
while (jsonReader.hasNext()) { // Loop through all keys

3
    String key = jsonReader.nextName(); // Fetch the next key

4
    if (key.equals("organization_url")) { // Check if desired key

5
        // Fetch the value as a String

6
        String value = jsonReader.nextString();
7
         
8
        // Do something with the value

9
        // ...

10
                 
11
        break; // Break out of the loop

12
    } else {
13
        jsonReader.skipValue(); // Skip values of other keys

14
    }

The above code processes the JSON response as a stream of tokens. Therefore, it consumes very little memory. However, because it has to process every single token one after another, it can be slow while handling large responses.

After you've extracted all the required information, you must always call the close() method the JsonReader object so that it releases all the resources it holds.

1
jsonReader.close();

You must also close the connection by calling the disconnect() method of the HttpURLConnection object.

1
myConnection.disconnect();

7. Using Different HTTP Methods

HTTP-based REST interfaces use HTTP methods to determine the type of operation that has to be performed on a resource. In the previous steps, we made use of the HTTP GET method to perform a read operation. Because the HttpURLConnection class uses the GET method by default, we didn't have to specify it explicitly.

To change the HTTP method of your HttpURLConnection object, you must use its setRequestMethod() method. For example, the following code snippet opens a connection to an endpoint that belongs to httpbin.org and sets its HTTP method to POST:

1
URL httpbinEndpoint = new URL("https://httpbin.org/post");
2
HttpsURLConnection myConnection
3
        = (HttpsURLConnection) httpbinEndpoint.openConnection();
4
 
5
myConnection.setRequestMethod("POST");

As you might already know, POST requests are used to send data to the server. By writing to the output stream of the connection, you can easily add any data to the body of the POST request. However, before you do so, you must make sure that you call the setDoOutput() method of the HttpURLConnection object and pass true to it.

The following code snippet shows you how to send a simple key-value pair to the server:

1
// Create the data

2
String myData = "message=Hello";
3
 
4
// Enable writing

5
myConnection.setDoOutput(true);
6
 
7
// Write the data

8
myConnection.getOutputStream().write(myData.getBytes());

8. Caching Responses

It is always a good idea to cache HTTP responses. By doing so, you can not only reduce your app's bandwidth consumption, but also make it more responsive. From API level 13 onwards, the Android SDK offers a class called HttpResponseCache, which allows you to easily implement caching without making any changes to your networking logic.

To install a cache for your application, you must call the install() method of the HttpResponseCache class. The method expects an absolute path specifying where the cache must be installed and a number specifying the size of the cache. You can use the getCacheDir() method if you don't want to specify the absolute path manually.

The following code snippet installs a cache whose size is 100,000 bytes:

1
HttpResponseCache myCache = HttpResponseCache.install(
2
                                getCacheDir(), 100000L);

Once the cache is installed, the HttpURLConnection class starts using it automatically. To check if your cache is working, you can use its getHitCount() method, which returns the number of HTTP responses that were served from the cache.

1
if (myCache.getHitCount() > 0) {
2
    // The cache is working

3
}

How to Build an Android App With an API

Prerequisites

Before you start developing any Android app, you should install Android Studio and have the latest Android SDK installed through Android Studio.

Getting Started

Open Android Studio and create a new project with an empty activity.

new projectnew projectnew project

Click Next, configure the settings as shown, and click Finish.

ConfigureConfigureConfigure

Wait a few minutes for Android Studio to create your project files. Your project structure should now look like this.

project structureproject structureproject structure

The next thing is to add INTERNET permissions in the manifest file. Go to manifests/AndroidManifest.xml and enable INTERNET permission for the app to access API calls.

1
<uses-permission android:name="android.permission.INTERNET" /> 

Our app UI will consist of the following elements:

  • a button
  • a progress dialog
  • a text view

When the user clicks on the button, the progress dialog will display a message letting the user know the information is being processed. Once the data is fetched from the API, it will be displayed by the text view.

Open the activity_main.xml file and add the components as shown below.

1
<?xml version="1.0" encoding="utf-8"?>
2
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
3
xmlns:tools="http://schemas.android.com/tools"
4
android:layout_width="match_parent"
5
android:layout_height="match_parent"
6
android:orientation="vertical"
7
android:padding="30dp"
8
tools:context=".MainActivity">
9
10
<Button
11
    android:id="@+id/displayData"
12
    android:layout_width="200dp"
13
    android:layout_height="wrap_content"
14
    android:layout_gravity="center"
15
    android:layout_marginTop="20dp"
16
    android:text="Click to Show  Users"
17
    android:textColor="@color/cardview_dark_background"
18
    android:textSize="18sp" />
19
20
<TextView
21
    android:id="@+id/results"
22
    android:layout_width="wrap_content"
23
    android:layout_height="wrap_content"
24
    android:layout_marginTop="50dp"
25
    android:visibility="gone"
26
    android:textColor="@color/design_default_color_primary"
27
    android:textSize="18sp" />
28
29
</LinearLayout>
30

Define the URL and the UI components at the top of the Main_activity.java file.

1
public class MainActivity extends AppCompatActivity {
2
    
3
    String myUrl = "https://api.mocki.io/v1/a44b26bb";
4
    TextView resultsTextView;
5
    ProgressDialog progressDialog;
6
    Button displayData;
7
    
8
    
9
    //the rest of the code
10
    
11
    }

Next, use findViewById() to hook the components on the onCreate method.

1
    protected void onCreate(Bundle savedInstanceState) {
2
        super.onCreate(savedInstanceState);
3
        setContentView(R.layout.activity_main);
4
        
5
        resultsTextView = (TextView) findViewById(R.id.results);
6
        displayData = (Button) findViewById(R.id.displayData);
7
8
    }

Defining an AsyncTask

Create the AsyncTask method for downloading network data from the API, and implement the onPreExecute(), doInBackground(), and onPostExecute() methods.

1
public class MyAsyncTasks extends AsyncTask<String, String, String> {
2
3
4
        @Override
5
        protected void onPreExecute() {
6
            super.onPreExecute();
7
            // display a progress dialog to show the user what is happening
8
            
9
10
        @Override
11
        protected String doInBackground(String... params) {
12
13
            // Fetch data from the API in the background.
14
         
15
        }
16
17
        @Override
18
        protected void onPostExecute(String s) {
19
20
21
      // show results 
22
        }
23
24
    }

On the onPreExecute() method, display a progress dialog that lets the user know what is happening.

1
@Override
2
protected void onPreExecute() {
3
    super.onPreExecute();
4
    // display a progress dialog for good user experiance

5
    progressDialog = new ProgressDialog(MainActivity.this);
6
    progressDialog.setMessage("processing results");
7
    progressDialog.setCancelable(false);
8
    progressDialog.show();
9
}

On the doInBackground method, create a URL connection and read the data from the API. Surround the operation with try-catch clauses to catch any exceptions that might occur when fetching data from the API.

1
@Override
2
protected String doInBackground(String... params) {
3
4
    // Fetch data from the API in the background.

5
    
6
    String result = "";
7
    try {
8
        URL url;
9
        HttpURLConnection urlConnection = null;
10
        try {
11
            url = new URL(myUrl);
12
            //open a URL coonnection

13
14
            urlConnection = (HttpURLConnection) url.openConnection();
15
16
            InputStream in = urlConnection.getInputStream();
17
18
            InputStreamReader isw = new InputStreamReader(in);
19
20
            int data = isw.read();
21
22
            while (data != -1) {
23
                result += (char) data;
24
                data = isw.read();
25
26
            }
27
            
28
            // return the data to onPostExecute method

29
            return result;
30
31
        } catch (Exception e) {
32
            e.printStackTrace();
33
        } finally {
34
            if (urlConnection != null) {
35
                urlConnection.disconnect();
36
            }
37
        }
38
39
    } catch (Exception e) {
40
        e.printStackTrace();
41
        return "Exception: " + e.getMessage();
42
    }
43
    return result;
44
}

On the onPostExecute() method, dismiss the progress dialog and display the results to the user with a text view.

1
        @Override
2
        protected void onPostExecute(String s) {
3
            
4
            // dismiss the progress dialog after receiving data from API

5
            progressDialog.dismiss();
6
            try {
7
8
                JSONObject jsonObject = new JSONObject(s);
9
10
                JSONArray jsonArray1 = jsonObject.getJSONArray("users");
11
12
                JSONObject jsonObject1 =jsonArray1.getJSONObject(index_no);
13
                String id = jsonObject1.getString("id");
14
                String name = jsonObject1.getString("name");
15
                String my_users = "User ID: "+id+"\n"+"Name: "+name;
16
17
                //Show the Textview after fetching data

18
                resultsTextView.setVisibility(View.VISIBLE);
19
                
20
                //Display data with the Textview

21
                resultsTextView.setText(my_users);
22
23
            } catch (JSONException e) {
24
                e.printStackTrace();
25
            }
26
        }

Finally, set an onClickLIstener on the button and execute MyAsyncTasks when a user clicks the button.

1
        // implement setOnClickListener event on displayData button

2
        displayData.setOnClickListener(new View.OnClickListener() {
3
            @Override
4
            public void onClick(View v) {
5
                // create object of MyAsyncTasks class and execute it

6
                MyAsyncTasks myAsyncTasks = new MyAsyncTasks();
7
                myAsyncTasks.execute();
8
            }
9
        });

Final Result

Android APIAndroid APIAndroid API

Conclusion

There are thousands of REST APIs available for you to freely use in your Android apps. By using them, you can make your app more informative, interesting, and feature-rich. In this tutorial, you learned how to use the HttpURLConnection class to consume such REST APIs and create an HTTP response cache that keeps your app's bandwidth usage low. You also learned how to fetch and display data from an API.

If you think using HttpURLConnection is hard, you should give third-party libraries such as Volley a try. Libraries like this use the HttpURLConnection class internally, but provide lots of convenient methods that allow you to make your code more concise and readable.

To learn more about networking on the Android platform, you can refer to Android's Network Operations guide.