قالب وردپرس درنا توس
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 enables developers to interact with external services. These are the commands that the developer of the service has decided will be used to access certain features of their applications. This is called an interface because a good API should have commands that make it intuitive to interact with.

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

It’s easy to see how interaction with these types of services can expand the features of an app. In fact, the vast majority of successful apps in the Play Store will use at least one web API!

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

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 the eXtensible Markup Language. If you are an Android developer, you are probably already familiar with XML from building your layouts and saving variables.

XML is easy to understand and usually places keys within triangle mounts, followed by their values. It looks a bit like HTML:


Jeff
32

JSON, on the other hand, stands for “Javascript Object Notation.” It is a short hand to send data online. As an 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 units (persons in this case) that can be described by key / value pairs. We use these in our Android apps by turning them into objects just like we normally would, using classes.

See also: How to use classes in Java

To see this in action, we need to find a web API that we can easily use. In this example, we use JSON Placeholder. This is a free REST API specifically for testing and prototyping, which is perfect for teaching you a new skill! REST is a special architectural “style” that has become the standard for communication over networks. REST-compatible systems are called “RESTful” and share certain features. However, you do not have to worry about it right now.

Set up our project for retrofitting 2

In this example, we also use something called 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 on our part. This can then be used, for example, to view tweets from Twitter or to check the weather. It significantly reduces the amount of work we need to do to make it work.

See also: Consume API: Get started with retrofitting on Android

First of all, we need to add Internet access to our Android Manifest file to ensure that our app can go online. Here is what you need to include:

We also need to add an addiction if we are to make Retrofit 2 work in our app. To add to your build.gradle file at the module level:

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 will convert JSON data to a Java object for us (a process called deserialization). We can do it manually, but using tools like this makes life a lot easier!

In fact, there are later versions of Retrofit that make some changes. If you want to be up to date, you can check out the official website.

Converts JSON to Java objects

A “Route” is a URL that represents an end point of the API. If we look at JSON Placeholder, do you see that we have options like “/ posts” and “/ comments? PostId = 1 ”. There is a good chance that you have seen such URLs when you surf the web!

Click on / post and you will see a large amount of data in JSON format. This is a dummy text that mimics what a page full of social media posts looks like. This is the information we want to get from our app and then displayed 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 build objects from deserialized data. For this purpose, you create a new class in your project and call it “PlaceholderPost”. This will need variables that correspond to the data we get from the / post page (“body”, “ID” etc.). We will get that information from the web API, so we need a getter for each of them.

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;
    }

}

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

Interface files

Then we need a new interface file. You create this in the same way as you create a class: by clicking on your package name in the project window and selecting “New> Class” but here you select “Interface” where you enter the name. An interface file contains methods that are later implemented by a class. I have called my “PlaceholderAPI”.

This interface only needs a single method to retrieve all data from “/ Post”. If you look at the JSON again, you will notice that the curly brackets are in square brackets. This means that we have a lot of items, which is why we want to create a list for them. The objects are instances of our “PlaceholderPost” that we just created, so that’s what we enter here!

For those who are very new to programming, keep in mind that red lines probably mean you have not imported a class. Just click on the highlighted statement and press alt + return to do this automatically.

(I can not 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();

}

Displays the content

Go back to your main activity. We can build a nice layout to show all this information, but to keep things nice and simple, I will just stick to the layout as it is.

To use retrofit, we must 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 send the rest of the URL here. We then want to use our interface:

Call call = placeholderAPI.getPosts();

Now we just need to call the method! Because things have been too simple so far, Android throws a small key by preventing you from doing this on the main thread. The reason, of course, is that if the process takes too long, it will stop freezing the app! This applies when using any web API. It makes sense, but it’s not very convenient when we just want to do a tutorial. Fortunately, we do not have to create a second thread ourselves because Retrofit actually does everything for us.

We now get an onResponse and onFailure callback. onFailure is of course where we need to deal with any errors.

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

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

The whole 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!");
    }
}

Ends

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

Of course, there are countless other web APIs, and they all work in their own way. Some require additional SDKs to use or different libraries. Similarly, there are many other actions in addition to the “GET” request that we showed here. For example, you can use “POST” 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 when you combine the power and flexibility of Android with the enormous resources available online.


Source link