Skip to main content

How to use a web API from your Android app

Web API in Android

Credit: 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:

<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:

[{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:

<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:

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

We also need something called Gson:

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.

[{
    "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:

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:

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:

 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:

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:

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.



source https://www.androidauthority.com/use-web-api-android-1152645/

Comments

Popular posts from this blog

5 tips to Voice Speech Recognition in Android Marshmallow

Android Marshmallow landed on our Android devices. The opportunity for us to offer a small compilation of tricks to try immediately. The latest version of the Google OS starts (very gently, unhurriedly) to be offered on other devices as Nexus. You will find on Android TM, in the coming weeks, a compilation of the best tips for Android 6.0 Marshmallow. It starts slowly with a video featuring the 10 essential tips & tricks of this new version of the little green robot OS. To continue, we offer a selection of five "tricks" on the management of the battery on Android 6.0 Marshmallow. To enjoy longer your newly updated mobile. Follow the guide. then continue with 5 tips to tame the super-assistant Google Now on Tap. Here you will find 5 "tips" to manage in the best way your applications. We then discuss the quick tips to navigate more easily on this version of the Google OS. We enchanters with features focused on safety and the protection of personal data. We co...

Energy Android TV Play turns your TV into a Smart TV

ENERGY SISTEM Android Energy TV Play, you have a smart TV with Android operating system allows you to convert any traditional TV has announced the launch of a new product. Energy Android TV Play can be connected to the TV to enjoy f the size of a flash drive, a smart phone, a tablet and a computer unconsolidated is a lightweight device. System 1.6 GHz, DDR3 1GB of RAM and a dual-core processor can be expanded using external USB devices, which is the internal memory of 8 GB. It also integrates WiFi and a USB port for connecting external devices. One of its outstanding features, it is easily connected to the TV screen by screen cast application to display the contents of any terminal, making any phone or tablet is synchronized with iOS or Android. All ENERGY SISTEM products one click In addition, through streaming media service applications, images, video or other multimedia content, and game play is the ability to share. With integrated WiFi, the device you want from t...

How to run Python apps on any platform

Credit: Adam Sinicki / Android Authority Want to know how to run Python? It sounds simple, but it can actually be tricky to figure this out. In this post, we’ll discuss how to test your Python code, as well as how to run Python in other contexts: online for example, or as a packaged app. Sometimes, the thing holding you back from learning to code can be extremely simple. I remember wanting to learn to program when I was younger – or learning to take what I’d learned from BASIC on the ZX Spectrum and apply that to a modern environment. My problem? I didn’t know “where” to program. Once I understood C# or Java, where would I enter the code and how would I run it? And whenever I asked someone, they would look at me blankly. What kind of a question is that? Thing is, I had never needed an IDE or an interpreter before. Machines like the ZX Spectrum and Tatung Einstein (any other Einstein users out there?) simply booted up with a prompt to code into! Many people have a similar iss...