DEV Community

Cover image for How to Make API Calls in Android Using Kotlin
Gaurav
Gaurav

Posted on

How to Make API Calls in Android Using Kotlin

In modern mobile app development, integrating with RESTful APIs is a common task. Often, these APIs require different types of HTTP methods, such as GET, POST, PUT, and DELETE, for different operations. In this blog post, we will walk through how to create a generic utility in Kotlin that allows you to call any of these methods seamlessly.

Why You Need a Generic API Call Utility

Rather than creating different functions for each HTTP method, it's more efficient to have a single method that can handle all types of requests. This helps in writing clean and maintainable code.

Step-by-Step Guide to Create a Generic API Utility

1. Setting Up the API Utility Class
Let’s start by creating an API utility class that handles all types of HTTP methods (GET, POST, PUT, DELETE). We'll use HttpURLConnection for this purpose, as it's a part of the Java standard library and works well for simple HTTP requests.

Here's the code for the utility:

class API {

    companion object {
        // Function to handle all HTTP methods
        fun callApi(apiUrl: String, token: String, httpMethod: String, requestModel: Any? = null): String {
            val response = StringBuilder()

            try {
                val url = URL(apiUrl)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = httpMethod // Set the HTTP method (GET, POST, PUT, DELETE)

                // Set request headers for JSON format and authorization
                connection.setRequestProperty("Content-Type", "application/json")
                connection.setRequestProperty("Accept", "application/json")
                connection.setRequestProperty("Authorization", "Bearer $token")

                // Send request body for POST/PUT methods
                if (httpMethod == "POST" || httpMethod == "PUT") {
                    connection.doOutput = true
                    requestModel?.let {
                        val jsonInput = Gson().toJson(it)
                        OutputStreamWriter(connection.outputStream).use { os ->
                            os.write(jsonInput)
                            os.flush()
                        }
                    }
                }

                // Handle the response
                val responseCode = connection.responseCode
                if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                    BufferedReader(InputStreamReader(connection.inputStream, "utf-8")).use { br ->
                        var responseLine: String?
                        while (br.readLine().also { responseLine = it } != null) {
                            response.append(responseLine?.trim())
                        }
                    }
                } else {
                    // Handle error response
                    BufferedReader(InputStreamReader(connection.errorStream, "utf-8")).use { br ->
                        var responseLine: String?
                        while (br.readLine().also { responseLine = it } != null) {
                            response.append(responseLine?.trim())
                        }
                    }
                    println("Error Response Code: $responseCode, Message: ${connection.responseMessage}")
                }
            } catch (e: Exception) {
                e.printStackTrace()
                return e.message.toString()
            }

            return response.toString()
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

2. How It Works

HTTP Method: The function accepts an HTTP method (POST, GET, PUT, DELETE) and sets it dynamically using the requestMethod property.
Authorization: The Authorization header is set using a Bearer token.
Request Body: For POST and PUT methods, the request body is serialized to JSON using Gson and sent along with the request.
Response Handling: If the response code is 200 OK or 201 Created, the response body is read and returned. Otherwise, the error message is captured.

3. How to Call the Utility

You can use this utility in your Android application for any type of API call.

Example 1: POST Request

val apiUrl = "https://api.example.com/v1/resource"
val token = "your_token_here"

val requestBody = mapOf(
    "field1" to "value1",
    "field2" to "value2"
)

val response = API.callApi(apiUrl, token, "POST", requestBody)
println(response)
Enter fullscreen mode Exit fullscreen mode

Example 2: GET Request

val apiUrl = "https://api.example.com/v1/resource/1"
val token = "your_token_here"

// No request body for GET
val response = API.callApi(apiUrl, token, "GET")
println(response)
Enter fullscreen mode Exit fullscreen mode

Example 3: PUT Request

val apiUrl = "https://api.example.com/v1/resource/1"
val token = "your_token_here"

val requestBody = mapOf(
    "field1" to "new_value1",
    "field2" to "new_value2"
)

val response = API.callApi(apiUrl, token, "PUT", requestBody)
println(response)
Enter fullscreen mode Exit fullscreen mode

Example 4: DELETE Request

val apiUrl = "https://api.example.com/v1/resource/{id}"
val token = "your_token_here"

// No request body for DELETE
val response = API.callApi(apiUrl, token, "DELETE")
println(response)
Enter fullscreen mode Exit fullscreen mode

4. Adding Network Permissions
Don't forget to add the necessary permissions for network access in your AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
Enter fullscreen mode Exit fullscreen mode

Conclusion

By creating a generic API utility, you can easily handle multiple types of HTTP requests (GET, POST, PUT, DELETE) in your Android applications. This approach keeps your code clean, reusable, and easy to maintain, ensuring efficient communication with external APIs.

With this setup, you can quickly integrate with RESTful APIs in any Android project, saving time and reducing complexity.

That's all for today.

And also, share your favourite web dev resources to help the beginners here!

Connect with me:@ LinkedIn

Top comments (0)