Welcome to the first lesson of Building Robust API Clients in Kotlin. In this course, you will learn how to handle common scenarios when working with APIs more effectively. One of the key aspects of working with APIs is error handling. Handling errors gracefully not only helps in building robust applications but also enhances user experience by providing meaningful feedback when things go wrong. Our goal in this lesson is to help you manage these outcomes effectively.
Understanding HTTP Status Codes
When you send a request to an API, the server responds with an HTTP status code. These codes indicate the result of your request. Understanding them is essential for effective error handling. Here's a brief overview:
2xx (Success): Indicates that the request was successfully received, understood, and accepted. For example, a 200 status code means OK.
4xx (Client Errors): Suggests that there was an error in the request made by your client. For example, 404 means the requested resource was not found.
5xx (Server Errors): Indicates that the server failed to fulfill a valid request. A common code here is 500, which means an internal server error.
By paying attention to these codes, you can determine whether your request succeeded or if there was a problem that needs addressing.
Raising Exceptions for Unsuccessful Status Codes
Examples: Non-existent Route
Examples: POST Request Without Required Title
Examples: Handling Broader Request-Related Issues
Summary and What's Next
In this lesson, you learned about the importance of error handling in API requests and were introduced to effective techniques using HTTP status codes and try-catch blocks. These practices are crucial for creating robust applications that deal with errors gracefully and provide clear feedback to users.
You are now equipped to practice these skills through hands-on exercises that will reinforce the concepts you've learned. As you move forward, you'll continue to build on these techniques to engage with more advanced API features. Remember, practicing error handling is key — experiment with different scenarios to see how errors are managed and how they affect your applications.
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal
Kotlin's OkHttp library is a popular choice for handling HTTP requests and responses. It provides a more modern and flexible approach compared to HttpURLConnection. We can use OkHttp to check the response code and throw exceptions for unsuccessful status codes.
Consider the following example, which fetches todo items from an API using OkHttp:
Kotlin
import okhttp3.OkHttpClientimport okhttp3.Requestimport java.io.IOException// Base URL for the APIval baseUrl = "http://localhost:8000"// Function to fetch all todos with error handlingfun fetchTodos() { val client = OkHttpClient() // Create a request object with the /todos endpoint val request = Request.Builder() .url("$baseUrl/todos") .build() try { // Execute the request and get the response client.newCall(request).execute().use { response -> // Check if the response code is 4xx or 5xx and throw an exception if so if (!response.isSuccessful) { throw IOException("HTTP error occurred: ${response.code} ${response.message}") } // If no exception was thrown, print success message println("Todos fetched successfully!") } } catch (e: IOException) { // Handle any HTTP or other errors that occur println(e.message) }}// Call the function to fetch todosfetchTodos()
In this example, we use OkHttpClient to create and execute a request. We then check the isSuccessful property of the response to determine if the status code indicates an error (4xx or 5xx). If an error is detected, an IOException is thrown, making error handling straightforward.
The use {} block in the examples is crucial for ensuring that the response is closed properly, thereby preventing resource leaks. This is particularly important when dealing with resources like network responses, as failing to close them can lead to memory leaks and other resource management issues.
Following our discussion on raising exceptions for unsuccessful status codes, let's delve into specific scenarios where errors might occur. In this first example, a GET request is sent to a non-existent route, leading to an HTTP error because a 404 Not Found status code is returned.
Kotlin
fun fetchInvalidRoute() { val client = OkHttpClient() // Create a request object with a non-existent endpoint val request = Request.Builder() .url("$baseUrl/invalid-route") .build() try { // Execute the request and get the response client.newCall(request).execute().use { response -> // Check if the response code is 4xx or 5xx and throw an exception if so if (!response.isSuccessful) { throw IOException("HTTP error occurred: ${response.code} ${response.message}") } } } catch (e: IOException) { // Handle any HTTP or other errors that occur println(e.message) }}// Call the function to fetch from an invalid routefetchInvalidRoute()
This will produce the following output indicating that the requested resource was not found:
text
HTTP error occurred: 404 Not Found
Continuing with error handling, the next scenario involves sending a POST request without a required field, the 'title', resulting in an HTTP error due to a 400 Bad Request.
Kotlin
fun postWithoutTitle() { val client = OkHttpClient() // Create a request object with the /todos endpoint val requestBody = "{}".toRequestBody("application/json".toMediaType()) val request = Request.Builder() .url("$baseUrl/todos") .post(requestBody) .build() try { // Execute the request and get the response client.newCall(request).execute().use { response -> // Check if the response code is 4xx or 5xx and throw an exception if so if (!response.isSuccessful) { throw IOException("HTTP error occurred: ${response.code} ${response.message}") } } } catch (e: IOException) { // Handle any HTTP or other errors that occur println(e.message) }}// Call the function to post without a titlepostWithoutTitle()
The following output shows a 400 Bad Request error, indicating missing required fields:
text
HTTP error occurred: 400 Bad Request
Finally, let's examine how to handle broader request-related issues. This example demonstrates a scenario where an exception occurs due to connectivity issues or other problems external to the HTTP response itself.
Kotlin
fun fetchWithInvalidUrl() { val client = OkHttpClient() // Create a request object with an invalid URL val request = Request.Builder() .url("http://invalid-url") .build() try { // Execute the request and get the response client.newCall(request).execute().use { response -> // Check if the response code is 4xx or 5xx and throw an exception if so if (!response.isSuccessful) { throw IOException("HTTP error occurred: ${response.code} ${response.message}") } } } catch (e: IOException) { // Handle any HTTP or other errors that occur println("Other error occurred: ${e.message}") }}// Call the function to fetch with an invalid URLfetchWithInvalidUrl()
When a connection cannot be established, the following output will provide details about the connectivity issue:
text
Other error occurred: no protocol: http://invalid-url
These examples build on the principles of exception handling we previously discussed, offering more detailed insights into managing errors effectively in different contexts within your API interactions.