Generating Thumbnails from Videos using ApyHub’s API: A step-by-step guide in Go
Tags: videothumbnail, apyhub, api, go
Published: 2024-02-07 07:59:36

# Introduction:

As we have discussed in the [previous article](https://apyhub.com/blog/video-thumbnails-for-seo), video thumbnails have a lot of benefits and possible uses, including better visual appeal, improved user experience, and of course a boost in brand identity and recognition. In this tutorial, we will get a bit more technical - focusing on the [ApyHub video thumbnail generator API](https://apyhub.com/utility/video-thumbnail).

No worries, this will try to be as simple and detailed as possible. We will go step by step, guiding you through every little detail. We will cover the API's core functionalities, including how to request thumbnails from videos using simple HTTP requests.

Moreover, we will show something even more cool: How to custamize thumbnail dimensions and extract thumbnails from various time points within a video. Finally, we will show how to implement the generated thumbnails into your applications or websites.

## Prerequisite:

- Standard IDE ( VSCode/Sublime)
- [Go 1.1 and Above](https://go.dev/doc/install)
- [An ApyHub account](https://apyhub.com/auth/signup)

### Step 1: Set up the project

First things first — We’ll start by creating a new directory and initialize it with Go modules.

```bash
> mkdir video-thumbnail-api-golang
> cd video-thumbnail-api-golang
> go mod init video-thumbnail-generator
```

*Note: `go mod init video-thumbnail-generato`r initializes a new Go module by creating a go.mod file in the current directory which tracks the project's dependencies.*

### Step 2: Create a new file `main.go`, and open it in your IDE or code editor:

This file will contain the logic to interact with ApyHub’s Video Thumbnail Generator API.

![ide](https://i.postimg.cc/0NR5r2Bm/Screenshot-2024-01-25-at-6-35-38-PM.png)

### Step 3: Import the necessary packages:

In this step, the necessary packages are imported to make a successful API call.

```go
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"io/ioutil"
)
```

- **bytes**: Required for buffering and manipulating byte slices.
- **encoding/JSON**: Required for encoding and decoding JSON, the format used for the API request and response.
- **fmt**: Provides I/O formatting functions.
- **net/http**: Required to make HTTP requests to the API.
- **io/iouti**l: Helps in reading the response body

### Step 4: Define the payload:

This code defines a struct `ThumbnailRequest` representing the data you will send to the API and tells Go how to encode the data into JSON.

```go
type ThumbnailRequest struct {
    VideoURL   string `json:"video_url"`
    StartTime  string `json:"start_time"`
    Duration   string `json:"duration"`
    Size       string `json:"size"`
}
```

### Step 5: Creating the HTTP Request:

We are creating a `generateThumbnail` function, which will encapsulate the logic to generate Thumbnail using [ApyHub’s Generate Video Thumbnail API](https://apyhub.com/utility/video-thumbnail).

```go
func generateThumbnail(apiToken, videoURL string) {
apiUrl:= "https://api.apyhub.com/generate/video-thumbnail/url?output=test-sample.mp4"
    payload := ThumbnailRequest{
        VideoURL:  videoURL,
        StartTime: "0",
        Duration:  "2",
        Size:      "400x300",
    }
jsonData, err := json.Marshal(payload)

    if err != nil {
        fmt.Println("Error marshalling data:", err)
        return
    }

    req, err := http.NewRequest("POST", apiUrl, bytes.NewBuffer(jsonData))
    if err != nil {
        fmt.Println("Error creating request:", err)
        return
    }
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("apy-token", apiToken)
    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Error sending request to the API:", err)
        return
    }
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Println("Error reading response body:", err)
        return
    }
    fmt.Println("Response:", string(body))
}
```

### Step 6: Create the main Function:

This function initialises variables for our `apiToken` and the `videoURL`, then calls the `generateThumbnail` function with these parameters to generate a thumbnail for the specified video.

```go
func main() {
    apiToken := "YOUR_APY_TOKEN" // Replace with your APY token
    videoURL := "https://assets.apyhub.com/samples/sample.mp4"
    generateThumbnail(apiToken, videoURL)
}
```

### Step 7: Running the Program:

Finally, execute the program by running go run main.go to your terminal.

```go
go run main.go
```

*Tip:  `go run` command is used in Go to compile and run a Go program in a single step. allows you to quickly execute a Go source file without explicitly building an executable binary.*

This will make an API request to APYHub to generate a thumbnail from the specified video URL, and you should see the API response in your terminal.

```go
Response: { "data" : "outputFileURL" }
```

Note: You can also find the complete code in this [repository.](https://github.com/iamspathan/video-thumbnail-generator-apyhub) Also, if you’re looking for a NodsJS integration guide, you can find it here.

## Conclusion

That's it! It wasn't so difficult, right? We have successfully integrated the [Video Thumbnail API](https://apyhub.com/utility/video-thumbnail) using Go Lang!

Using this service, we can generate video thumbnails from literally any part of a video file or URL (e.g. YouTube). This way, we automate extracting thumbnails from videos, allowing for efficient and consistent extraction of thumbnails without the need for any manual work.

The [ApyHub Video Thumbnail API](https://apyhub.com/utility/video-thumbnail) can also be integrated into existing workflows and platforms, making it easy to incorporate thumbnail extraction into existing processes.

Good luck with using the API. Looking forward to any feedback on [Discord.](https://discord.gg/3mYBZvymDf)