analitics

Pages

Showing posts with label google-api-python-client. Show all posts
Showing posts with label google-api-python-client. Show all posts

Monday, November 19, 2018

Using Google Classroom API with python.

Today I read and test Google API with the Python programming language.
You can find a good example here.
The example shows how to read with Google Classroom API, v1.
This example can be used as a default example if you want to use googlescopes.
The Google documentation tells us:
This document lists the OAuth 2.0 scopes that you might need to request to access Google APIs, depending on the level of access you need. Sensitive scopes require review by Google and have a sensitive indicator on the Google Cloud Platform (GCP) Console's OAuth consent screen configuration page. Many scopes overlap, so it's best to use a scope that isn't sensitive. For information about each method's scope requirements, see the individual API documentation.
The script use credentials.json file created by the Google project in the folder with the python script.
The script creates automatically when the authorization flow completes a token.json file.
The control of the project can be used with the Google Cloud Console.
The result of the example script can be seen in the next image:

Sunday, June 24, 2018

Python 3.6.4 : Using python client with blogger API .

I used a new project into console cloud google.
I used the google-api-python-client from here with OAuth service.
You need to create a project and add the blogger API to use it.
For credentials, I used OAuth with the JSON file from google.
This is the source code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function

__author__ = 'Catalin George Festila ( catafest , mythcat )'

import sys

from oauth2client import client
from googleapiclient import sample_tools


def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'blogger', 'v3', __doc__, __file__,
      scope='https://www.googleapis.com/auth/blogger')

  try:

      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'])

      blogs = service.blogs()

      # Retrieve the list of Blogs this user has write privileges on
      thisusersblogs = blogs.listByUser(userId='self').execute()
      for blog in thisusersblogs['items']:
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))

      posts = service.posts()

      # List the posts for each blog this user has
      for blog in thisusersblogs['items']:
        print('The posts for %s:' % blog['name'])
        request = posts.list(blogId=blog['id'])
        while request != None:
          posts_doc = request.execute()
          if 'items' in posts_doc and not (posts_doc['items'] is None):
            for post in posts_doc['items']:
              print('  %s (%s)' % (post['title'], post['url']))
          request = posts.list_next(request, posts_doc)

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run'
      'the application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)
The content of the folder project named google_api_python.
c:\Python364\google_api_python>dir
06/24/2018  08:27 PM             1,096 blogger.dat
06/24/2018  07:49 PM             2,599 blogger.py
06/24/2018  08:24 PM               309 client_secrets.json
06/24/2018  08:26 PM                76 debug.log
               4 File(s)          4,080 bytes
               2 Dir(s)  201,382,006,784 bytes free
You need to add the client_id and client_secret from google project into file client_secrets.json.
Run the python script:
c:\Python364\google_api_python>python.exe blogger.py
The google will ask you about the authentification and will run the script:

Google show us all the infos about this project into dashboard:

Wednesday, June 28, 2017

The Google API Client Library python module.

This python module named Google API Client Library for Python is a client library for accessing the Plus, Moderator, and many other Google APIs, according to the official link.
C:\Python27\Scripts>pip install --upgrade google-api-python-client
Collecting google-api-python-client
  Downloading google_api_python_client-1.6.2-py2.py3-none-any.whl (52kB)
    100% |################################| 61kB 426kB/s
...
Successfully installed google-api-python-client-1.6.2 ...
The example I used is this:
from oauth2client.client import flow_from_clientsecrets
import httplib2
import apiclient
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_id.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 = apiclient.discovery.build('blogger', 'v3', http=http)
    return service

if __name__ == '__main__':
    served = get_service()
    print dir(served.blogs)
    users = served.users()

    # Retrieve this user's profile information
    thisuser = users.get(userId='self').execute()
    print('This user\'s display name is: %s' % thisuser['displayName'].encode('utf-8'))

    blogs = served.blogs()

    # Retrieve the list of Blogs this user has write privileges on
    thisusersblogs = blogs.listByUser(userId='self').execute()
    for blog in thisusersblogs['items']:
        print('The blog named \'%s\' is at: %s' % (blog['name'], blog['url']))
The result of this script is this:
C:\Python27>python.exe google_001.py
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', 
'__get__', '__getattribute__', '__hash__', '__init__', '__is_resource__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', 
'__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self']
This user's display name is: Cătălin George Feștilă
The blog named 'python-catalin' is at: http://python-catalin.blogspot.com/
The blog named 'graphics' is at: http://graphic-3d.blogspot.com/
The blog named 'About me and my life ...' is at: http://catalin-festila.blogspot.com/
The blog named 'pygame-catalin' is at: http://pygame-catalin.blogspot.com/
About google settings then you need to have a google account to use Google’s API.
The first step for accessing the Google Developer’s Console.
Then navigate to the Developer Console’s projects page and create a new project for our application by clicking the Create project button and then enable blogger API.
Enter your projects name and hit create.
Click the Go to Credentials button with these settings like in the next image:

Download this credential information in JSON format, in this case, is the client_id.json file.
When you run for the first time this script you will see an open HTML page with your auth code.
The script example named google_001.py will come with this message:
C:\Python27>python.exe google_001.py
C:\Python27\lib\site-packages\oauth2client\_helpers.py:255: UserWarning: Cannot access credentials.dat: No such file or directory
  warnings.warn(_MISSING_FILE_MESSAGE.format(filename))
Enter the auth code:
Put this auth code and allow the script using the open page and your google account using Allow button.
Now you can run the example.