Search code examples
google-app-enginegoyoutube-apiyoutube-data-apigoogle-api-go-client

how to fetch youtube playlist videos using Go on app engine


Using Api key I was able to fetch the videos in a playlist from Api Explorer. Execute without OAuth fetched the results json. Here is the link.
https://developers.google.com/apis-explorer/?hl=en_US#p/youtube/v3/youtube.playlistItems.list?part=snippet&playlistId=PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T&_h=2&

Implementing the same call using Go on App engine fails with below error:

 Get https://www.googleapis.com/youtube/v3/playlistItems?alt=json&part=snippet&playlistId=PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T: http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://cloud.google.com/appengine/docs/go/urlfetch/

Here is the code I use:

import (
    "net/http"
    "code.google.com/p/google-api-go-client/googleapi/transport"
    "code.google.com/p/google-api-go-client/youtube/v3"
    "log"
)

    var service *youtube.Service
    func init() {
        var err error
        log.Println("Apikey = ", apiKey)
        client := &http.Client{Transport: &transport.APIKey{Key: apiKey}}
        service, err = youtube.New(client)
        if err != nil {
            log.Println("ERROR in creating youtube New client ", err)
        }
        var items *youtube.PlaylistItemListResponse
        if items, err = service.PlaylistItems.List("snippet").PlaylistId("PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T").Do(); err != nil {
            log.Println("Error in fetching playlist items ", err) //this line shows the error
        }
        log.Println(Jsonify(items))
    }

As of now, I run my code on local dev server i.e goapp serve

What is missing? How do I fetch youtube playlist videos using v3 api and ApiKey?


Solution

  • Found the solution. Below code did the task for me.

    func FetchVideos(w http.ResponseWriter, r *http.Request) {
        var service *youtube.Service
        ctx := appengine.NewContext(r)
    
        transport := &transport.APIKey{
            Key:       apiKey,
            Transport: &urlfetch.Transport{Context: ctx}}
        client := &http.Client{Transport: transport}
    
        var err error
        service, err = youtube.New(client)
        if err != nil {
            log.Println("ERROR in creating youtube New client ", err)
        }
        var items *youtube.PlaylistItemListResponse
        if items, err = service.PlaylistItems.List("snippet").PlaylistId("PLHyTuYqPkZCzt7mWZ4hmmrRdjLJiw6O2T").Do(); err != nil {
            log.Println("Error in fetching playlist items ", err)
        }
        log.Println(Jsonify(items))