5

I'm trying to use the blog functions from Google API gdata. I tried my best following the documentation but I failed very badly. Can anybody tell me how can I use the Google blogger API? My code is pretty messed up and now I'm out of clue.

EDIT FULL WORKING CODE :) :

from oauth2client.client import OAuth2WebServerFlow
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage

#flow = OAuth2WebServerFlow(client_id='', #ID
#                           client_secret='', #SECRET ID
#                           scope='https://www.googleapis.com/auth/blogger',
#                           redirect_uri='urn:ietf:wg:oauth:2.0:oob')

#auth_uri = flow.step1_get_authorize_url()
# Redirect the user to auth_uri on your platform.

# Open a file
#fo = open("foo.txt", "wb")
#fo.write( auth_uri +"\n");
#fo.close()

#credentials = flow.step2_exchange( raw_input ( ) ) 


storage = Storage('a_credentials_file')
#storage.put(credentials)

credentials = storage.get()

http = httplib2.Http()
http = credentials.authorize(http)

service = build('blogger', 'v3', http=http)

users = service.users() 

# Retrieve this user's profile information
thisuser = users.get(userId='self').execute()
print('This user\'s display name is: %s' % thisuser['displayName'])
ryspbsk
  • 111
  • 3
  • 11
  • Please read [How-to-Ask](http://stackoverflow.com/help/how-to-ask) and then add relevant information to your question. "I failed very badly" is not a specific programming problem. – Mailerdaimon Jun 16 '16 at 06:45
  • I just don't have a clue how to use this API: `https://developers.google.com/blogger/docs/3.0/api-lib/python` I want to use these functions: `https://developers.google.com/apis-explorer/#p/blogger/v3/` but I don't know how to make it work with `aouth 2.0` .. – ryspbsk Jun 16 '16 at 06:48
  • Have you read the OAuth guide? https://developers.google.com/api-client-library/python/guide/aaa_oauth – Mailerdaimon Jun 16 '16 at 06:56
  • **CODE UPDATED first post** Woah! I actually read that but I still couldn't figure out how to use it although it was very obvious. You're a life saviour. Thanks a ton. Now the final step is remaining. `users = service.users()` This line is throwing error `AtrributeError: Object Resource has no attribute 'users'`. Now Just how exactly can I access BLOGGER API CLASS? – ryspbsk Jun 16 '16 at 07:35
  • 1
    I found it. It was `service = build('blogger', 'v3', http=http)`. Thank you so much Mailerdaimon. I upvoted of your question since you did not post an answer here. Thank you very much. You saved me from a very big headache. – ryspbsk Jun 16 '16 at 07:42
  • Glad that I could help. :) – Mailerdaimon Jun 16 '16 at 08:07
  • How do i create this 'a_credentials_file' ? Is there a format? – Arindam Roychowdhury Jan 27 '17 at 06:43
  • You have to uncomment the lines ( obviously starting with # tag in my first post ) and then you have to run it. This will ask you for input and provide the details. Once you terminate/close the program then you have to comment the same lines again because now you will have the credentials file created. – ryspbsk Jan 28 '17 at 08:12

3 Answers3

4

While I was myself trying to find a solution, I found this. Then after some modifications, the code finally worked. It successfully print all details about you blog site.

from oauth2client.client import flow_from_clientsecrets
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
import webbrowser

def get_credentials():
    scope = 'https://www.googleapis.com/auth/blogger'
    flow = flow_from_clientsecrets(
        'client_secrets.json', scope,
        redirect_uri='urn:ietf:wg:oauth:2.0:oob')
    storage = Storage('credentials.dat')
    credentials = storage.get()

    if  not credentials or credentials.invalid:
        auth_uri = flow.step1_get_authorize_url()
        webbrowser.open(auth_uri)
        auth_code = raw_input('Enter the auth code: ')
        credentials = flow.step2_exchange(auth_code)
        storage.put(credentials)
    return credentials

def get_service():
    """Returns an authorised blogger api service."""
    credentials = get_credentials()
    http = httplib2.Http()
    http = credentials.authorize(http)
    service = build('blogger', 'v3', http=http)
    return service

if __name__ == '__main__':
    served = get_service()
    blogs = served.blogs()
    blog_get_obj = blogs.get(blogId='123456789123456')
    details = blog_get_obj.execute()
    print details

The results of print will look like:

{u'description': u'Look far and wide. There are worlds to conquer.',
 u'id': u'8087466742945672359',
 u'kind': u'blogger#blog',
 u'locale': {u'country': u'', u'language': u'en', u'variant': u''},
 u'name': u'The World Around us',
 u'pages': {u'selfLink': u'https://www.googleapis.com/blogger/v3/blogs/1234567897894569/pages',
            u'totalItems': 2},
 u'posts': {u'selfLink': u'https://www.googleapis.com/blogger/v3/blogs/1245678992359/posts',
            u'totalItems': 26},
 u'published': u'2015-11-02T18:47:02+05:30',
 u'selfLink': u'https://www.googleapis.com/blogger/v3/blogs/9874652945672359',
 u'updated': u'2017-06-29T19:41:00+05:30',
 u'url': u'http://www.safarnuma.com/'}
Arindam Roychowdhury
  • 5,927
  • 5
  • 55
  • 63
  • What should be supplied in `auth_code = raw_input('Enter the auth code: ')`? – AAAA Mar 12 '20 at 18:33
  • @MariuszSiatka I don't remember correctly but I think, a URL will open in browser and you have to copy that here when asked. Refer the link mentioned in my answer. It tells you the exact flow. – Arindam Roychowdhury Mar 13 '20 at 09:33
0

This is an updated and long-term stable implementation, taken from this answer and edited a bit for Blogger API v3.

All methods in the official documentation can be called on blogger_service variable of this code.

import os
import pickle

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/blogger', ]


# we check if the file to store the credentials exists
if not os.path.exists('credentials.dat'):

    flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
    credentials = flow.run_local_server()

    with open('credentials.dat', 'wb') as credentials_dat:
        pickle.dump(credentials, credentials_dat)
else:
    with open('credentials.dat', 'rb') as credentials_dat:
        credentials = pickle.load(credentials_dat)

if credentials.expired:
    credentials.refresh(Request())

blogger_service = build('blogger', 'v3', credentials=credentials)

users = blogger_service.users() 
# Retrieve this user's profile information
thisuser = users.get(userId='self').execute()
print('Your display name is: %s' % thisuser['displayName'])
sirDeniel
  • 43
  • 6
0

You can use goco

pip install goco

then use this code:

from goco import Goco

GoogleApi = Goco("path\\to\\client_secret.json", "path\\to\\credentials.storage")

MyBlog = GoogleApi.connect(scope='Blogger', service_name='blogger', version='v3')

Posts = MyBlog.posts().list(blogId='desired-blog-id').execute()

print(Posts)

you can also connect to any google service via this module.