Youtube subscription api [Error]
-
11-06-2021 - |
Question
I am trying to subscribe to youtube channel via api. As i am not good with xml so need your help. Original link to docs: https://developers.google.com/youtube/2.0/developers_guide_protocol_subscriptions Or
In short here is what written in youtube docs:
Adding a subscription
To create a subscription, you send a POST request that identifies the YouTube user name for the authenticated user who is creating the subscription. The body of the request is an XML entry that contains the following elements:
The <category>
tag identifies the type of subscription that the user is creating. Set the tag's term attribute value to user to indicate that the user is subscribing to another user's activities (uploading videos, ratings, marking videos as favorites, etc.), or set the term attribute value to channel to indicate that the user is subscribing to a channel.
The <yt:username>
tag identifies the channel or the user whose activity is being subscribed to.
Subscribing to a channel
POST /feeds/api/users/default/subscriptions HTTP/1.1
Host: gdata.youtube.com
Content-Type: application/atom+xml
Content-Length: CONTENT_LENGTH
Authorization: Bearer ACCESS_TOKEN
GData-Version: 2
X-GData-Key: key=DEVELOPER_KEY
<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007">
<category scheme="http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat"
term="channel"/>
<yt:username>GoogleDevelopers</yt:username>
</entry>
My Question
How do i code the post request ? I tried with simple html form method post. But it didnt worked. I got the following error.
Content-Type application/x-www-form-urlencoded is not a valid input type.
Solution
Since you are using an HTML Form Post, it's setting the content type to application/x-www-form-urlencoded
but the required content type is application/atom+xml
To do what you want, you'll need to use javascript to post (I recommend jQuery for simplicity).
var data = //XML Data for post
$.ajax({
url://Youtube Subscribe Post URL,
type:"POST",
data:data,
Authorization: //ACCESS_TOKEN,
GData-Version: '2',
X-GData-Key: 'key=' //DEVELOPER_KEY,
contentType:"application/atom+xml",
dataType:"xml",
success: function(){
alert('subscribd');
}
});
I haven't tested it, but you should get the idea. Ensure you replace the comments with the actual values for your app.
Note that this may run into cross-domain issues.