How to Call Rest Api from Android App

Introduction

Video Tutorial:


In today’s world, most applications rely on APIs (Application Programming Interfaces) to interact with data and services from different sources. Android app development is no exception, as it involves making calls to one or more APIs, which enables the app users to access the required data or services. In this blog post, we will focus on how to call Rest APIs from an Android app.

The Challenge of Calling Rest API from Android App

Though there are plenty of tutorials on how to call Rest API from Android, many beginners still find it challenging to get started. This is mainly because they lack proper guidance, which is essential for mastering the different tools and libraries required to complete the process. However, with the right preparation, it can be simple and easy to integrate Rest API in your Android app.

Things You Should Prepare Before Using Rest API In Your Android App

1. Android Studio: Install the latest version of Android Studio on your computer.
2. Android Virtual Device: Create or configure an Android Virtual Device to test your application on different device configurations.
3. Android Emulator: Set up the emulator to run your app on virtual devices.
4. API Endpoint: Get the required API endpoint URL from the provider of the API.
5. HTTP Library: Choose the appropriate HTTP library that will make your API calls easier to handle.

Method 1: Using HttpURLConnection Class

One of the methods to make Rest API calls from Android app is using the HttpURLConnection class to handle the HTTP operations. The steps and the codes are presented in this section.

Steps:
1. Create a URL object using the API endpoint URL.
2. Open an HTTP connection to the URL.
3. Set the required request methods and headers.
4. Read the response from the input stream.
5. Parse the response and handle errors.

Codes:
"`
try {
// 1. Create a URL object
URL url = new URL(api_endpoint_url);

// 2. Open an HTTP connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

// 3. Set the request methods and headers
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("username", "myusername");
urlConnection.setRequestProperty("Authorization", "Bearer mytoken");

// 4. Read the response from the input stream
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
String response = inputStreamToString(in);

// 5. Parse the response and handle errors
handleResponse(response);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
"`

Pros:
– Low-level API, which allows developers to control the connection and handle errors more efficiently.
– No need to add any external libraries since HttpURLConnection is already included in the Android SDK.

Cons:
– The code can be lengthy and time-consuming to write.
– The error handling can be complicated for a beginner.

Method 2: Using OkHttp Library

Another method to call Rest API from Android app is by using a third-party HTTP library like OkHttp. OkHttp is efficient and easy-to-use, which makes the process of making network requests less complicated.

Steps:
1. Add the OkHttp dependency to the build.gradle file.
2. Create an instance of OkHttpClient and define the request with the required parameters.
3. Send the request with the OkHttpClient instance.
4. Execute the request and handle the response.

Codes:

"`
// 1. Add the OkHttp dependency
def okhttp_version = "4.9.0"
implementation("com.squareup.okhttp3:okhttp:$okhttp_version")

// 2. Create an OkHttpClient instance
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(api_endpoint_url)
.header("Authorization", "Bearer mytoken")
.build();

// 3. Send the request and execute it
Response response = client.newCall(request).execute();

// 4. Handle the response
if (response.isSuccessful()) {
String body = response.body().string();
handleResponse(body);
} else {
throw new IOException("Error: " + response);
}
"`

Pros:
– Easy-to-use and write, which makes it a beginner-friendly choice.
– Good for handling complex requests and responses.

Cons:
– The library’s size can slow down app performance.
– The developer must add the library to the project.

Method 3: Using Retrofit Library

Retrofit is another popular HTTP client library that simplifies the process of calling Rest API in an Android app. It helps to manage complex API requests and responses using a simple interface.

Steps:
1. Add the Retrofit and Gson dependencies to the build.gradle file.
2. Define the Rest API interface with the required request methods and parameters.
3. Create a Retrofit instance that points to the base URL.
4. Use the Retrofit instance to create a Rest API service object.
5. Call the Rest API methods and handle the response in the callback.

Codes:

"`
// 1. Add the Retrofit and Gson dependencies
def retrofit_version = "2.9.0"
def gson_version = "2.8.6"
implementation("com.squareup.retrofit2:retrofit:$retrofit_version")
implementation("com.squareup.retrofit2:converter-gson:$retrofit_version")
implementation("com.google.code.gson:gson:$gson_version")

// 2. Define the Rest API interface
public interface ApiService {
@GET("/api/users/{userId}")
Call getUser(@Path("userId") long userId, @Query("apiKey") String apiKey);
}

// 3. Create a Retrofit instance
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

// 4. Create a Rest API service object
ApiService apiService = retrofit.create(ApiService.class);

// 5. Call the Rest API methods and handle the response in the callback
Call call = apiService.getUser(userId, apiKey);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
UserResponse userResponse = response.body();
handleResponse(userResponse);
}

@Override
public void onFailure(Call call, Throwable t) {
handleFailure(t);
}
});
"`

Pros:
– Allows the developer to work with complex APIs in a simplified manner.
– Retrofit utilizes the power of annotations, reducing the boilerplate code required to make API requests.

Cons:
– Requires additional libraries, which can increase app size.
– Developers may face challenges when consuming APIs that do not follow standard REST protocols.

Why Can’t I Call Rest API in My Android App and How to Fix It?

1. Network Connection Issue: Ensure that your device or emulator has proper network connectivity, and the API endpoint is reachable.
2. Permissions Issue: If your app’s targetSdkVersion is higher than 22, you might need to add permission requests in the manifest file to allow network requests.
3. Time Constraints: Network requests consume time to complete; hence, you should ensure proper integration of the network requests, such as placing them in a background thread.
4. API Compatibility Issue: Ensure your API endpoint and client version’s compatibility by following the provider’s API documentation.

Additional Tips

1. Use HTTPS instead of HTTP to secure your API communication.
2. Use libraries that provide caching capabilities to enhance app performance and reduce network requests.
3. Use other tools like Stetho, which can help you monitor network requests and responses.

5 FAQs about Calling Rest API from Android App

Q1: What is the difference between GET and POST request method?

A: GET requests are used to retrieve data from a server, while POST requests are used to submit data to a server.

Q2: Do I need to add internet permission to my app to make Rest API calls?

A: Yes, you must add the internet permission to your app to allow it to make network requests.

Q3: Is it possible to make Rest API calls using AsyncTask?

A: Yes, it is possible. However, it is not a recommended practice since AsyncTask may cause memory leaks and may not handle configuration changes correctly.

Q4: What should I do if I face an SSLHandshakeException error?

A: To fix this error, you can try disabling SSL verification in the network connection or ensure that your server’s SSL certificate is properly installed.

Q5: How can I debug my Rest API calls?

A: You can use different debugging tools like Android Studio Debugger, Stetho, or logging statements to debug your app’s Rest API calls.

In Conclusion

Making Rest API calls in Android app development is an integral part of fetching data and services from different applications. In this blog post, we have explored different methods like HttpURLConnection, OkHttp, and Retrofit, which are commonly used in Android development for making Rest API calls. To avoid common issues like network connection issues or permissions issue, ensure you have the necessary preparation, and be aware of the common reasons you can’t make a Rest API call. With the right preparation and knowledge, making Rest API calls in Android can be simple and straightforward.