Search results for

All search results
Best daily deals

Affiliate links on Android Authority may earn us a commission. Learn more.

How to use a web API from your Android app

Learn how to use a web API from within an Android app using Retrofit!
By

Published onMarch 14, 2021

Web API in Android
Adam Sinicki / Android Authority

A Web API is an online “application programming interface” that allows developers to interact with external services. These are the commands that the developer of the service has determined will be used to access certain features of their program. It is referred to as an interface because a good API should have commands that make it intuitive to interact with.

An example of this might be if we want to get information about a user from their social media account. That social media platform would likely have a web API for developers to use in order to request that data. Other commonly used APIs handle things like advertising (AdMob), machine learning (ML Kit), and cloud storage.

It’s easy to see how interacting with these types of services could extend the functionality of an app. In fact, the vast majority of successful apps on the Play Store will use at least one web API!

In this post, we’ll explore how to use a web API from within an Android app.

How a Web API works

Most APIs work using either XML or JSON. These languages allow us to send and retrieve large amounts of useful information in the form of objects.

XML is eXtensible Markup Language. If you are an Android developer, then you’re probably already familiar with XML from building your layouts and saving variables.

XML is easy to understand and generally places keys inside triangle brackets, followed by their values. It looks a bit like HTML:

Code
<client>
<name>Jeff</name>
<age>32</age>
</client>

JSON, on the other hand, stands for “Javascript Object Notation.” It is a short-hand for sending data online. Like XML or a CSV file, it can be used to send “value/attribute pairs.”

Here the syntax looks a little different, though:

Code
[{client: {“name”:”Jeff”, “age”: 32}}]

These are “data objects” in that they are conceptual entities (people in this case) that can be described by key/value pairs. We use these in our Android apps by turning them into objects just as we normally would, with the use of classes.

See also: How to use classes in Java

To see this in action, we need to find a Web API that we can use readily. In this example, we will be using JSON Placeholder. This is a free REST API specifically for testing and prototyping, which is perfect for learning a new skill! REST is a particular architectural “style” that has become standard for communicating across networks. REST-compliant systems are referred to as “RESTful” and share certain characteristics. You don’t need to worry about that right now, however.

Setting up our project for Retrofit 2

For this example, we’ll also be using something called Retrofit 2. Retrofit 2 is an extremely useful HTTP client for Android that allows apps to connect to a Web API safely and with a lot less code on our part. This can then be used, for example, to show Tweets from Twitter, or to check the weather. It significantly reduces the amount of work we need to do to get that working.

See also: Consuming APIs: Getting started with Retrofit on Android

First up, we need to add internet permission to our Android Manifest file to make sure our app is allowed to go online. Here is what you need to include:

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

We also need to add a dependency if we are going to get Retrofit 2 to work in our app. So in your module-level build.gradle file add:

Code
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

We also need something called Gson:

Code
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Gson is what is going to convert the JSON data into a Java object for us (a process called deserialization). We could do this manually, but using tools like this makes life much easier!

There are actually later versions of Retrofit that make a few changes. If you want to be up-to-the-moment, check out the official website.

Converting JSON to Java object

A “Route” is a URL that represents an endpoint for the API. If we take a look at JSON Placeholder, you’ll see we have options such as “/posts” and “/comments?postId=1”. Chances are you will have seen URLs like this yourself while browsing the web!

Click on /posts and you’ll see a large amount of data in JSON format. This is a dummy text that mimics the way a page full of posts on social media looks. It is the information we want to get from our app and then display on the screen.

Code
[{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
  {
    "userId": 1,
    "id": 3,
    "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
    "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
  }

To handle this information, we’re going to need a class that can build objects from the deserialized data. To that end, create a new class in your project and call it “PlaceholderPost”. This will need variables that correspond to the data we’re getting from the /posts page (“body”, “ID” etc.). We’ll be getting that information from the web API, so we need a getter for each of them.

The final class should look like this:

Code
public class PlaceholderPost {

    private int userID;
    private int id;
    private String title;
    private String body;

    public int getUserId() {
        return userID;
    }

    public int getId() {
        return id;
    }

    public String getTitle() {
        return title;
    }

    public String getBody() {
        return body;
    }

}

This could just as easily be users on Twitter, messages on Facebook, or information about the weather!

Interface files

Next, we need a new interface file. You create this the same way you create a class: by clicking on your package name in the project window and choosing “New > Class” but here you’re selecting “Interface” underneath where you enter the name. An interface file contains methods that are later implemented by a class. I’ve called mine “PlaceholderAPI”.

This interface needs just a single method to retrieve all the data from “/Post”. If you take a look at that JSON again, you’ll notice that the curly brackets are inside square brackets. This means that we have an array of objects, which is why we want to build a list for them. The objects are instances of our “PlaceholderPost” that we just made, so that’s what we’re putting in here!

For those that are very new to programming, remember that any red lines probably mean you haven’t imported a class. Just click on the highlighted statement and press alt+return to do this automatically.

(I can’t imagine anyone using this as an early programming lesson but you never know!)

This looks like so:

Code
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface PlaceholderAPI {

    @GET("posts")
    Call<List> getPosts();

}

Displaying the content

Now, hop back into your main activity. We could build a fancy layout for displaying all this data, but to keep things nice and simple, I’m just going to stick with the layout as it is.

To use Retrofit, we’re going to need to create a new Retrofit object. We do this with the following lines of code:

Code
Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .build();

As you can see, we’re passing in the rest of the URL here. We then want to use our interface:

Code
Call<List> call = placeholderAPI.getPosts();

Now we just need to call the method! Because things have been too easy so far, Android does throw a little spanner in the works by preventing you from doing this on the main thread. The reason, of course, is that if the process takes too long, it will end up freezing the app! This is true when using any Web API. It makes sense, but it’s not terribly convenient when we just want to make a tutorial. Fortunately, we don’t need to create a second thread ourselves as Retrofit actually does all that for us.

We’ll now get an onResponse and onFailure callback. onFailure is, of course, where we need to handle any errors.

onResponse does not mean that everything went smoothly, however. It simply means that there was a response; that the website exists. Should we get a 404 message, this would still be considered a “response.” Thus, we need to check again if the process went smoothly with isSuccessful(), which checks to see that the HTTP code is not an error.

To keep things really simple, I’m going to display just one piece of data from one of the objects we’ve received. To achieve this, I renamed the textView in the layout file to give it the id “text”. You can experiment with this yourself.

The full code looks like this:

Code
call.enqueue(new Callback<List>() {
            @Override
            public void onResponse(Call<List> call, Response<List> response) {

                if (response.isSuccessful()) {
                    List posts = response.body();
                    Log.d("Success", posts.get(3).getBody().toString());
                    TextView textView = findViewById(R.id.text);
                    textView.setText(posts.get(3).getBody().toString());
                } else {
                    Log.d("Yo", "Boo!");
                    return;
                }
            }

            @Override
            public void onFailure(Call<List> call, Throwable t) {
                Log.d("Yo", "Errror!");
            }

        });


        Log.d("Yo","Hello!");
    }
}

Wrapping up

At this point, you should have a good idea of how a web API works and why you want one. You would have also created your first app that uses a web API to do something potentially useful.

Of course, there are countless other web APIs, and each work in their own ways. Some will require additional SDKs to use or different libraries. Likewise, there are many other actions beyond the “GET” request we demonstrated here. For example, you can use “POST” in order to send data to the server, which is useful if you ever want your users to be able to post to social media from your apps.

The possibilities are endless once you combine the power and flexibility of Android with the huge resources available online.


For more developer news, features, and tutorials from Android Authority, don’t miss signing up for the monthly newsletter below!