Max Pierini
Max Pierini

Reputation: 23

YouTube python API v3 HttpError 400 subscriptionDuplicate

I'm using YouTube python API v3 to subscribe oauth2 authenticated users to new channels.

def add_subscription(youtube, channel_id):
  add_subscription_response = youtube.subscriptions().insert(
    part='id,snippet',
    body=dict(
      snippet=dict(
        resourceId=dict(
          channelId=channel_id
        )
      )
    )).execute()

  return add_subscription_response["id"], add_subscription_response["snippet"]["title"]


youtube = get_authenticated_service(args)

try:
    subscription_id,channel_title = add_subscription(youtube, args.channel_id)
except HttpError, e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
else:
    print "A subscription to '%s' was added." % channel_title

From https://developers.google.com/youtube/v3/docs/subscriptions/insert it seems that (or maybe, I understood that...) if the user is already subscribed to the channel described by channel_id, the function should raise an HttpError with e.resp.status=400 for a subscriptionDuplicate.

Nevertheless, if I try to subscribe to a channel the user is already subscribed to, the function normally returns a subscription_id and channel_title.

Shouldn't it raise HttpError 400?

And, if I'm not making mistakes and this is exactly the way the function should work, what could I do to check if the authenticated user is already subscribed to channel_id using only subscriptions().insert()?

I could call subscriptions().list() before, to check if user is subscribed:

def is_subscribed(youtube, channel_id):
        is_subscription_response = youtube.subscriptions().list(
                part='id',
                mine='true',
                forChannelId=channel_id
                ).execute()
        if len(is_subscription_response["items"]) == 0:
                return False
        else:
                return True

But this would increase quota usage...

Upvotes: 1

Views: 289

Answers (1)

KENdi
KENdi

Reputation: 7771

I also tried the Subscriptions: insert request and use it in a channel that I already subscribed and I'm not getting the error subscriptionDuplicate. I don't know why the API did not return this error.

So to answer your question about how to check if the authenticated user is already subscribed to channel_id, use the Subscriptions: list to know all the channel that you subscribed.

Here is the sample request, just replace the channelId with your own channelId.

https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&channelId=YOUR_CHANNEL_ID&key={YOUR_API_KEY}

Upvotes: 0

Related Questions