Downloading Files from an API

Today's focus will be on downloading files from an API using Kotlin and OkHttp. Understanding how to retrieve files efficiently not only enhances your technical skills but also broadens your application's capabilities. In this lesson, we'll explore a practical scenario using our To-Do list API, which, in addition to managing tasks, supports handling text files such as notes. These notes can be downloaded or uploaded through the /notes endpoint, allowing functionality for storing supplementary information. For example, users might keep notes about a meeting or important reminders. By understanding how to interact with this endpoint, you can effectively manage notes within your application. By the end of this lesson, you'll know how to request a file from an API, save it locally, and verify its contents.

Let's dive into downloading files with precision and confidence!

Basic File Download with GET Requests

GET requests are fundamental for retrieving files from an API. When you send a GET request using OkHttp, your client communicates with the server at a specified URL, asking it to provide the file. The server responds with the file data, if available and permissible, along with an HTTP status code (like 200 OK).

Here's a basic example of downloading a file named welcome.txt from our API at http://localhost:8000/notes. This approach downloads the entire file at once, which is manageable for smaller files.

Kotlin
1import okhttp3.OkHttpClient 2import okhttp3.Request 3import java.io.File 4import java.io.IOException 5 6fun main() { 7 val client = OkHttpClient() 8 val baseUrl = "http://localhost:8000" 9 val noteName = "welcome.txt" 10 val request = Request.Builder() 11 .url("$baseUrl/notes/$noteName") 12 .build() 13 14 try { 15 client.newCall(request).execute().use { response -> 16 if (!response.isSuccessful) throw IOException("Unexpected code $response") 17 18 val file = File("downloaded_$noteName") 19 file.writeBytes(response.body!!.bytes()) 20 } 21 } catch (e: IOException) { 22 println("Error occurred: ${e.message}") 23 } 24}

This code sends a GET request and writes the full response content to a local file. This method works well for small files but can strain memory for larger files.

Leveraging GET Requests and Streaming

When dealing with large files, downloading them all at once can be inefficient and strain memory. To address this, you can read the response body in chunks, thus optimizing memory usage and maintaining efficiency.

Below is a detailed code example demonstrating how to download the same file using streaming:

Kotlin
1import okhttp3.OkHttpClient 2import okhttp3.Request 3import java.io.File 4import java.io.FileOutputStream 5import java.io.IOException 6 7fun main() { 8 val client = OkHttpClient() 9 val baseUrl = "http://localhost:8000" 10 val noteName = "welcome.txt" 11 val request = Request.Builder() 12 .url("$baseUrl/notes/$noteName") 13 .build() 14 15 try { 16 client.newCall(request).execute().use { response -> 17 if (!response.isSuccessful) throw IOException("Unexpected code $response") 18 19 val file = File("downloaded_$noteName") 20 FileOutputStream(file).use { output -> 21 response.body!!.byteStream().use { input -> 22 input.copyTo(output) 23 } 24 } 25 } 26 } catch (e: IOException) { 27 println("Error occurred: ${e.message}") 28 } 29}

Inside of the request call, the code begins by creating a File object to represent the local file where the downloaded content will be saved, naming it downloaded_welcome.txt. A FileOutputStream is then opened for this file, which facilitates writing data to it. The input stream from the response body is obtained using response.body!!.byteStream(), allowing the program to read the data from the response. The copyTo function is then employed to transfer data from the input stream to the output stream in chunks.

By utilizing streaming, even large files are downloaded efficiently. This technique is especially useful when file sizes increase.

Verification of Downloaded File Content

Once you've downloaded a file, it's imperative to verify its contents to ensure a successful transfer. In our example, after downloading, you can open the file and print its content to confirm data integrity:

Kotlin
1import java.io.File 2import java.io.IOException 3 4fun verifyFileContent(noteName: String) { 5 try { 6 val file = File("downloaded_$noteName") 7 val content = file.readText() 8 println(content) 9 } catch (e: IOException) { 10 println("File error occurred: ${e.message}") 11 } 12} 13 14fun main() { 15 val noteName = "welcome.txt" 16 verifyFileContent(noteName) 17}

If everything is functioning correctly, you should see an output similar to:

Plain text
1Welcome to Your Notes! 📝 2 3This is a sample note that comes with the application.

This step is essential for data verification. The familiar error-handling techniques come into play once more, using try-catch blocks to gracefully address any issues during the download and verification process.

Summary and Preparation for Practice

In this lesson, you explored two methods for downloading files from an API: a straightforward approach for smaller files and a more efficient streaming method for larger files. You've practiced verifying file integrity by reading its contents post-download and reinforced your knowledge of error management. As you proceed to the practice exercises, you'll have the opportunity to apply these skills, reinforcing your ability to manage API interactions effectively. Keep experimenting with different files and settings, as this will further enhance your understanding and proficiency. Exciting topics await, such as file uploads and handling paginated responses. Your journey in mastering API interactions continues!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal