I’m trying to use Youtube apis in my web application by following this guide https://developers.google.com/youtube/2.0/developers_guide_protocol_oauth2#OAuth2_Server_Side_Web_Applications_Flow I’ve done upto step 3 successfully and got the ** authorization code**.
Now I stuck with making POST request to this url https://accounts.google.com/o/oauth2/token
I want to make a request like this: (taken from the link I’ve given above)
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/ux5gNj-_mIu4DOD_gNZdjX9EtOFf&
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSe&
redirect_uri=http://localhost/oauth2callback&
grant_type=authorization_code
I tried something like this:
headers = {'Content-Type': 'application/x-www-form-urlencoded code=4/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&client_id=xxxxxxxxxxx.apps.googleusercontent.com&client_secret=xxxxxxxxxxxxxxxxx&redirect_uri=http://127.0.0.1:8000/information/youtube/&grant_type=authorization_code'}
r = requests.post(url, headers)
and I’m getting this error:
<Response [411]>
u'<!DOCTYPE html>\n<html lang=en>\n <meta charset=utf-8>\n <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">\n <title>Error 411 (Length Required)!!1</title>\n <style>\n *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}\n </style>\n <a href=//www.google.com/><img src=//www.google.com/images/errors/logo_sm.gif alt=Google></a>\n <p><b>411.</b> <ins>That\u2019s an error.</ins>\n <p>POST requests require a <code>Content-length</code> header. <ins>That\u2019s all we know.</ins>\n'
I know I’m wrong with the post request and I need your guidance on how to make it work.
Thanks!
Don’t put the data in the headers. Use the
datakwarg of.post()instead. Since a urlencoded POST body is the default there is also no need to specify it via theheadersargument.You can make this code even nicer by letting requests deal with the OAuth authentication via the requests-oauth extension: https://github.com/maraujop/requests-oauth#readme
Then you can perform your request without handling the OAuth parameters manually.