قالب وردپرس درنا توس
Home / Tips and Tricks / How to use a web API from your Android app

How to use a web API from your Android app



Web API in Android

A web API is an online application programming interface that developers can use to interact with external services. These are the commands that the developer of the service has set to access certain functions of his program. It’s called an interface because a good API should contain commands that allow intuitive interaction.

An example of this could be when we want to get information about a user from their social media account. This social media platform likely has a web API that developers can use to request this data. Other commonly used APIs include advertising (AdMob), machine learning (ML Kit), and cloud storage.

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

This post shows you how to use a web API in an Android app.

This is how a web API works

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

XML is an eXtensible markup language. If you’re an Android developer, you probably already knew XML from creating your layouts and storing variables.

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


Jeff
32

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

The syntax looks a little different here:

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

These are “data objects” because they are conceptual entities (in this case people) that can be described by key / value pairs. We use these in our Android apps by turning them into objects using classes as usual.

See also: Using classes in Java

To see this in action we need to find a web API that we can easily use. In this example we are using JSON placeholder. This is a free REST API specially designed for testing and prototyping, which is perfect for learning a new skill! REST is a special architectural “style” that has become the standard for communication over networks. RESTful systems are called “RESTful” and have certain characteristics. However, you don’t have to worry about that now.

Setting up our project for retrofit 2

In this example we’re also using Retrofit 2. Retrofit 2 is an extremely useful HTTP client for Android that allows apps to connect to a web API securely and with much less code. This can then be used, for example, to view tweets from Twitter or to check the weather. This greatly reduces the amount of work required to get this up and running.

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

First, we need to add an internet permission to our Android manifest file to make sure our app can go online. You need to include:

We also need to add a dependency in order for 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 will 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 a lot easier!

There are actually later versions of Retrofit that make some changes. If you want to be up to date, visit the official website.

Converting JSON to a Java object

A “route” is a URL that represents an end point for the API. If we look at JSON placeholders, you will see that we have options like “/ posts” and “/ comment? PostId = 1”. You may have seen such URLs yourself while surfing the internet!

Click / posts and you will see a huge amount of data in JSON format. This is dummy text that mimics the look of a page full of posts on social media. This is the information we receive from our app and then we want to display it on the screen.

[{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitaensequi sint nihil reprehenderit dolor beatae ea dolores nequenfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendisnqui 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 iurenvoluptatem occaecati omnis eligendi aut adnvoluptatem doloribus vel accusantium quis pariaturnmolestiae porro eius odio et labore et velit aut"
  }

To handle this information, we need a class that can create objects from the deserialized data. To do this, create a new class in your project and name it “PlaceholderPost”. This requires variables that correspond to the data we get from the / posts page (“body”, “ID”, etc.). We will get this information from the web API, so we need a getter for each one.

The last 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, news on Facebook, or information about the weather!

Interface files

Next we need a new interface file. You create this the same way as you create a class: click your package name in the Project window and choose New> Class. Here, however, select “Interface” under which you enter the name. An interface file contains methods that are later implemented by a class. I named my “PlaceholderAPI”.

This interface only needs a single method to get all of the data from “/ Post”. If you look again at this JSON you will notice that the curly braces are inside square brackets. This means that we have a number of objects, which is why we want to make a list for them. The objects are instances of our “PlaceholderPost” that we just created, so let’s put that in here!

If you are new to programming, keep in mind that red lines likely mean you haven’t imported a class. Just click the highlighted instruction and hit Alt + Back to do it automatically.

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

It looks like this:

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

public interface PlaceholderAPI {

    @GET("posts")
    Call getPosts();

}

View the content

Now return to your main activity. We could create a fancy layout for displaying all of this data, but to keep things nice and simple I’ll just stick to the layout as it is.

In order to use retrofit, we need to create a new retrofit object. We do that with the following lines of code:

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

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

Call call = placeholderAPI.getPosts();

Now we just have to call the method! Since things have been too easy so far, Android throws a little wrench into work by preventing you from doing so in the main thread. The reason, of course, is that the app will freeze if the process takes too long! This applies when using any web API. It makes sense, but it’s not particularly handy when we just want to create a tutorial. Fortunately, we don’t have to create a second thread ourselves as Retrofit does all of this for us.

We now receive an onResponse and an onFailure callback. In onFailure, of course, we have to deal with all errors.

However, onResponse doesn’t mean everything went smoothly. It just means there was an answer; that the website exists. Should we receive a 404 message, it is still considered a “reply”. So we need to check again that the process went smoothly is successful()This is used to check that the HTTP code is not an error.

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

The complete code looks like this:

call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response 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 call, Throwable t) {
                Log.d("Yo", "Errror!");
            }

        });


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

Wrap up

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

Of course, there are tons of other web APIs, each working in their own way. Some require additional SDKs or other libraries. There are also many other actions that go beyond the “GET” request shown here. For example, you can use POST to send data to the server. This is useful when you want your users to be able to post to Social media from your apps.

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


Source link