DEV Community

Cover image for Getting Started with HTTP Client Setup for POST Requests: Using a WhatsApp API as an Example
aricha
aricha

Posted on

Getting Started with HTTP Client Setup for POST Requests: Using a WhatsApp API as an Example

Introduction:

In this article, we'll walk you through the process of sending WhatsApp messages using Kotlin and Ktor, a versatile asynchronous web framework. We'll create a Kotlin class that encapsulates the functionality and provides a sendMessage method. This method will make a POST request to the WhatsApp API(APIWAP) and handle the response. Additionally, we'll explore using Kotlin coroutines to make the asynchronous HTTP request.

Requirements:

Before we dive into the code,

Lets get our ApiWap key required for our code.

  • Log In to ApiWap.com
  • Start Free Trial
  • Create an account
  • Create Instance
  • Scan watsapp account you want to connect(this is the particular account that will be sending the sms)
  • Finally get your api-key for later.

ensure you have the following dependencies added to your Kotlin project:

implementation ("io.ktor:ktor-client-core:1.6.10")
implementation("io.ktor:ktor-client-cio:1.6.10")
implementation("io.ktor:ktor-client-content-negotiation:$ktor_version")
implementation("io.ktor:ktor-serialization-kotlinx-json:$ktor_version")
Enter fullscreen mode Exit fullscreen mode

Creating the sendMessage Method:

Let's start by creating a Kotlin class and adding a method named sendMessage. This method will handle the entire process of sending a WhatsApp message, including making the API request and handling the response.

import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.utils.io.core.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable

class WhatsAppSender {

    suspend fun sendMessage(
        phoneNumber: String,
        message: String
    ): ResultData {
        val url = "https://api.apiwap.com/api/v1/whatsapp/send-message"
        val toPhoneNumber = phoneNumber
        val theMessage = message
        val type = "text"
        val apiKey = "apiwapKey"

        val payload = RequestDataDto(
            phoneNumber = toPhoneNumber,
            message = theMessage,
            type = type
        )

        try {
            val client = HttpClient(CIO) {
                install(ContentNegotiation) {
                    json()
                }
            }

            val response: HttpResponse = withContext(Dispatchers.IO) {
                client.post(url) {
                    url {
                        // You can add query parameters here if needed
                    }
                    contentType(ContentType.Application.Json)
                    headers {
                        append(HttpHeaders.Authorization, "Bearer $apiKey")
                    }
                    setBody(payload)
                }
            }

            return ResultData(data = response.readText())

        } catch (e: Exception) {
            return ResultData(error = e.message.toString())
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation of the sendMessage Method:

  1. We begin by defining the URL to the WhatsApp API and the required parameters such as the phone number, message, type, and your API key.

  2. Inside the try-catch block, we set up a Ktor HTTP client with CIO (Coroutine I/O) as the engine and configure it to handle JSON responses.

  3. We make an asynchronous POST request to the API using the client.post function. We set the request headers, content type, and the request body (payload).

  4. If the request is successful, we read the response text and wrap it in a ResultData object. This is done to provide a cleaner and more structured way to handle the response data.

  5. In case of an exception (e.g., network error or API response error), we catch the exception and return an error message as part of the ResultData.

ResultData and RequestDataDto:

To provide more context, here are the data classes used in the code:

@Serializable
data class ResultData(val data: String? = null, val error: String? = null)

@Serializable
data class RequestDataDto(
    val phoneNumber: String,
    val message: String,
    val type: String
)
Enter fullscreen mode Exit fullscreen mode

Conclusion:

You now have a Kotlin class that allows you to easily send WhatsApp messages using Ktor. The sendMessage method encapsulates the entire process, including setting up the client, making the API request, and handling the response. This code can be further integrated into your Kotlin project to automate WhatsApp messaging.

Top comments (0)