Pavan Kishore
Pavan Kishore

Reputation: 91

Youtube Thumbnail upload Failing with API

I am trying to upload a thumbnail for youtube video in this way:


import (
    "bufio"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)

func main() {

    url := "https://www.googleapis.com/youtube/v3/thumbnails/set?videoId=kU7okI-_vvU&key=[API_KEY]Type=media"
    imageRef, err := os.Open("test.png")
    if err != nil {
        log.Fatal("os.Open", err)
    }
    rd := bufio.NewReader(imageRef)

    req, err := http.NewRequest("POST", url, rd)
    if err != nil {
        log.Fatal("http.NewRequest", err)
    }

    log.Println(req.Body)

    req.Header.Add("authorization", "Bearer [ACCESS_TOKEN]")
    req.Header.Add("content-type", "image/png")

    res, err := http.DefaultClient.Do(req)
    if err != nil {
        log.Fatal("http.DefaultClient", err)
    }

    defer res.Body.Close()
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        log.Fatal("ioutil.ReadAll", err)
    }

    fmt.Println(res)
    fmt.Println(string(body))

}

I am getting this response:

  "error": {
    "code": 400,
    "message": "The request does not include the image content.",
    "errors": [
      {
        "message": "The request does not include the image content.",
        "domain": "youtube.thumbnail",
        "reason": "mediaBodyRequired",
        "location": "body",
        "locationType": "other"
      }
    ]
  }
}

I am including the image body in the POST request. Yet the respose says "The request does not include the image content.". Can anyone please help with this.

API requires that max file size be 2MB and I have ensured this.

Thank you.

PS: Although not shown in the code, result is tested with error handling.

Upvotes: 0

Views: 586

Answers (1)

stvar
stvar

Reputation: 6955

Using bare HTTP methods for invoking YouTube Data API can be quite tricky at times.

You should have been employing the Google API Client Library for Go instead. See also the official Go Quickstart.

In case you stick with your current code, you need to have the following:

  • the invoking URL should contain the parameter uploadType=media, and
  • the Content-Type header should be passed on to the HTTP call with a value of kind image/png (as already suggested above).
  • the Content-Length header should also be set by your code (since that's not done within the NewRequestWithContext function; see also this function's doc, as @Peter indicated below).

Also you have to change your URL, since, according to the official doc, the API endpoint's URL is:

https://www.googleapis.com/upload/youtube/v3/thumbnails/set.

Do notice that your URL is missing the /upload/ path component.

Upvotes: 1

Related Questions