How to use web APIs from your Android app

How to use web APIs from your Android app

 

How to use a web API from your Android app - Android Authority

 

  • A Web API is an onlineApplication Programming Interface” which allows the developers to interact with external services. APIs are the commands that the developer of the service has determined can be used to access certain features of the programs they have made. It is referred to as an interface because a good API should include commands that make it interactions with it to be intuitive.
  • For instance, suppose that we want to get information about a user from their social media handle. That social media platform would likely have a web API for the developers to use in order to request for some data. Other very commonly used APIs handle things like advertising the (AdMob), or machine learning (ML Kit), along with cloud storage.
  • It’s very easy to see how interacting with these types of services could extend the functionality of an app. In fact, majority of the successful apps on the Play Store will use at least one web API if not more!

In this blog we will be exploring how to use a web API from within an android app.

Working of a web API

 

What is Web API and why we use it ? - GeeksforGeeks

  • Most of the APIs work using either XML or JSON. These are the languages that allow us to send and retrieve large amounts of useful information in the form of an object.
  • XML is eXtensible Markup Language. If you are into android development then you might probably already be familiar with XML from having built your layouts and saving variables.
  • XML is a very easy to understand language and generally places keys inside triangle brackets, followed by the values included. It looks a bit like HTML, but don’t confuse it with HTML:

Code

<client>

<name>Jeff</name>

<age>32</age>

</client>

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

The syntax looks a little different, though:

Code

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

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

Setting up our own project for Retrofit 2

 

Using Retrofit 2 for web-services in Android with a simple demo project. | by Bipin Pandey | Resume and CV Builder App | Medium

 

  • For this example, we’ll also be using something called the Retrofit 2. Retrofit 2 is an immensely useful HTTP client for the Android that allows its apps to connect with the Web API safely and with a lot less code required on our part. This can then be used, for example, to show Tweets from Twitter, or even to check the weather. It significantly reduces the work load we need to do to get that working.
  • First off all, we need to add the internet permission to our Android Manifest file to ensure that our app is allowed to go online. Here is what you need to include in it:

Code

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

 

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’

We will be converting our data into Gson from the JSON data into a Java object for us (a process called deserialization). We could even do this manually, but using tools like this makes life much simpler!

Converting JSON to Java object

 

Java67: How to convert JSON String to Java Object? Gson/JSON Deserialization Example

 

  • A “Route” is a URL that represents the endpoint for an API. If we take a closer look at JSON Placeholder, you will be able to see we have options such as “/posts” and even “/comments?postId=1”. Chances are that you will have seen URLs like this yourself while browsing through the web!
  • Click on the /posts and you will see a large amount of data in the JSON format. This is a dummy text that mimics the way a page that is filled with posts on social media looks. It is the information that we want to get from our app and then display it 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 be able to handle this information, we’re going to need a class that can build objects from the de-serialized set of data. To that end, create a new class in the class project you have made and call it “PlaceholderPost”. This will be needing variables that correspond to the data set we are getting from the /posts page (“body”, “ID” etc.). We will be getting that information from the web API, so we will need a go-getter for each of them.

The final class code 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 would just as easily be users on Twitter, messages on Facebook, or information about the weather!

 

Thank you for reading this blog! I hope you have a wonderful rest of your day!!

If you have any doubts then do contact us or visit our site NullClass 

 

September 9, 2021

0 responses on "How to use web APIs from your Android app"

Leave a Message