Downloading Files from an API with Go

Downloading Files from an API

Welcome back! Today's focus will be on downloading files from an API using Go. 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 Go's net/http package, 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.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
)

func main() {
    // Base URL for the API
    baseURL := "http://localhost:8000"

    // Specify the note name to download
    noteName := "welcome.txt"

    // Send a GET request to download the file
    resp, err := http.Get(fmt.Sprintf("%s/notes/%s", baseURL, noteName))
    if err != nil {
        fmt.Printf("Error occurred: %v\n", err)
        return
    }
    defer resp.Body.Close()

    // Check for HTTP errors
    if resp.StatusCode != http.StatusOK {
        fmt.Printf("HTTP error occurred: %s\n", resp.Status)
        return
    }

    // Save the file locally
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error reading response body: %v\n", err)
        return
    }

    // Create (or overwrite) the file and write all data at once
    err = os.WriteFile("downloaded_"+noteName, body, 0644)
    if err != nil {
        fmt.Printf("Error writing file: %v\n", err)
    }
}

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.

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