Well, basicaly I'm lost with this task. I need to get all members of a group with the api google privedes. I'm starting with gmail quickstart example, first I have configure Api project and the OAuth client.
My first test was to see all the messages I have in my inbox, all ok. But to do the same with groups members I'm lost, I can't find the way to do it.
Any idea?
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import json
import requests
SCOPES = 'https://www.googleapis.com/auth/admin.directory.group.member'
def main():
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
response = requests.get("https://www.googleapis.com/admin/directory/v1/groups/example#test.com/members")
print(response)
The response is a:
<Response [401]>
Looks like you started with the gmail example and then modified to access the admin/group function
Check the admin docs here https://developers.google.com/admin-sdk/directory/v1/quickstart/python
here is the function, it will retrieve all groups email addressess
def retrieving_groups():
response_group = service.groups().list(customer='my_customer').execute()
for group in response_group['groups']:
print(group['email'])
Related
I'm coding a Python app to automatize invoices via a google docs API but I'm having errors with the code and I don't know how to solve it
# [START docs_quickstart]
from __future__ import print_function
import os.path
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/documents.readonly','https://www.googleapis.com/auth/documents','https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.readonly']
def main():
"""Shows basic usage of the Docs API.
Prints the title of a sample document.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
service = build('docs', 'v1', credentials=creds)
title = 'My Document'
body = {
'title': title
}
document = service.documents().create(body=body).execute()
print('Created document with title: {0}'.format(
document.get('title')))
except HttpError as err:
print(err)
if __name__ == '__main__':
main()
# [END docs_quickstart]
and this is the error code that I'm having
PS D:\Universidad\Proyectos de Programacion Propia\python\googledocsinvoice.restapi> python quickstart.py
<HttpError 403 when requesting https://docs.googleapis.com/v1/documents?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'#type': 'type.googleapis.com/google.rpc.ErrorInfo', 'reason': 'ACCESS_TOKEN_SCOPE_INSUFFICIENT', 'domain': 'googleapis.com', 'metadata': {'service': 'docs.googleapis.com', 'method': 'google.apps.docs.v1.DocumentsService.CreateDocument'}}]">
if you know some guide or complete tutorial to Automate Document Creation with the Google Docs API like invoices and replace encapsulation values like {{productID}} I will be very grateful
I saw the Automate document creation of google channel but it wasn't very helpful https://youtu.be/-dX-fWb3ogE
Best Regards
Make sure you also enable the Docs API in your Developers Console.
Delete the credential file ~/.credentials.json and token.json (if you ran the code before
Change the scope variable used for reading docs
var SCOPES = ['https://www.googleapis.com/auth/documents.readonly'];
to
var SCOPES = ['https://www.googleapis.com/auth/documents'];
Check more info on https://developers.google.com/docs/api/reference/rest/v1/documents/create#authorization-scopes and https://developers.google.com/docs/api/how-tos/authorizing
After the execution of code, API will authenticate again and then the issue should be resolved.
I am trying to retreive the classwork of each course from Google Classroom API.I have succeeded in getting all the courses, but I am stuck on the course work: <HttpError 403 when requesting https://classroom.googleapis.com/v1/courses/167997334462/courseWork?alt=json returned "Request had insufficient authentication scopes.">.
This is the code I am using:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students.readonly']
def main():
"""Shows basic usage of the Classroom API.
Prints the names of the first 10 courses the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
r"\test\credentials.json", SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('classroom', 'v1', credentials=creds)
# Call the Classroom API
course_work_results = service.courses().courseWork().list(courseId="167997334462").execute()
[...]
if __name__ == '__main__':
main()
I have generated the credidentials using admin account; I've also tried several different Scopes, but same error.
Could you guys please help me here?
I am using Python 3.9.
Thanks,
Alexandru
Since you are using the scope
https://www.googleapis.com/auth/classroom.coursework.students.readonly,
I assume you are a student.
Students are only allowed to access course work of the courses where they are accepted course participants.
Trying to retrieve the course work of another course will result in an 403 error.
If you are not a student, but an Admin of your Google Workspace domain, you should use a wider scope, e.g.
https://www.googleapis.com/auth/classroom.coursework.me.readonly.
Please mind that after changing the scopes in your source code you need to delete your token file to trigger new authentication flow.
Is it possible to create google contacts using the google contact APIs or people APIs?
I'm having trouble creating new contacts using the google APIs.
I'm searching for days and found the following information:
1 - Looks like the people API package comes to replace google contacts API
https://gsuite-developers.googleblog.com/2017/07/google-people-api-now-supports-updates.html
2 - Many people are unable to create new contacts with python 3+ using gdata and atom packages.
3 - people API appears as recommended by Gsuite
https://support.google.com/a/answer/6103110?hl=pt-BR
I would like to know if anyone is creating new contacts using these google APIs.
Is a g suite email required?
How do I get access token?
I've done all the setup on google cloud platform (enable APIs and auth2), i have the json file, secret key and client id
edit:
I am managing to list my 50 contacts with this code, I am having to modify the blocks to create new contacts
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/contacts']
def main():
"""Shows basic usage of the People API.
Prints the name of the first 10 connections.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('people', 'v1', credentials=creds)
# Call the People API
print('List 50 connection names')
results = service.people().connections().list(
resourceName='people/me',
pageSize=50,
personFields='names,emailAddresses').execute()
connections = results.get('connections', [])
for person in connections:
names = person.get('names', [])
if names:
name = names[0].get('displayName')
print(name)
if __name__ == '__main__':
main()
Since you already have auth working to list contacts, you should be able to do something like this to create one:
newContact = { "names": [{ "givenName": "John", "familyName": "Doe" }] }
result = service.people().createContact(body=newContact).execute()
The full definition of what can be in the body/person is here.
I've been finding such a mix of code examples. But nothing with a maintained library (google-auth) + full working example. google-api-python-client and oauth2client are no longer supported (https://github.com/googleapis/google-api-python-client/issues/651).
Here's a working example with deprecated libraries, but I'd like to see some examples that allow full access to the api (searching by albumId currently doesn't work with this library):
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
# Setup the Photo v1 API
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('photoslibrary', 'v1', http=creds.authorize(Http()))
# Call the Photo v1 API
results = service.albums().list(
pageSize=10, fields="nextPageToken,albums(id,title)").execute()
items = results.get('albums', [])
if not items:
print('No albums found.')
else:
print('Albums:')
for item in items:
print('{0} ({1})'.format(item['title'].encode('utf8'), item['id']))
You want to use google_auth instead of oauth2client, because oauth2client is deprecated.
You have already been able to use Photo API.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
For example, the sample script for authorizing can be seen at the Quickstart of Drive API with python. You can see the method for installing the library. Using this, your script can be modified as follows.
Modified script:
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def main():
credentialsFile = 'credentials.json' # Please set the filename of credentials.json
pickleFile = 'token.pickle' # Please set the filename of pickle file.
SCOPES = ['https://www.googleapis.com/auth/photoslibrary']
creds = None
if os.path.exists(pickleFile):
with open(pickleFile, 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
credentialsFile, SCOPES)
creds = flow.run_local_server()
with open(pickleFile, 'wb') as token:
pickle.dump(creds, token)
service = build('photoslibrary', 'v1', credentials=creds)
# Call the Photo v1 API
results = service.albums().list(
pageSize=10, fields="nextPageToken,albums(id,title)").execute()
items = results.get('albums', [])
if not items:
print('No albums found.')
else:
print('Albums:')
for item in items:
print('{0} ({1})'.format(item['title'].encode('utf8'), item['id']))
if __name__ == '__main__':
main()
About the script for retrieving the album list, your script was used.
When you run this script, at first, the authorization process is run. So please authorize the scope. This process is required to run only one time. But if you want to change the scopes, please delete the pickle file and authorize again.
References:
the Quickstart of Drive API with python
google-auth-library-python
google_auth_oauthlib package
Method: albums.list
If I misunderstood your question and this was not the direction you want, I apologize.
Added 1:
If you want to use the method of mediaItems.search, how about the following sample script? About the script for authorizing, please use above script.
Sample script:
service = build('photoslibrary', 'v1', credentials=creds)
albumId = '###' # Please set the album ID.
results = service.mediaItems().search(body={'albumId': albumId}).execute()
print(results)
Added 2:
You want to remove googleapiclient from my proposed above sample script.
You want to retrieve the access token using google_auth_oauthlib.flow and google.auth.transport.requests.
You want to retrieve the media item list in the specific album using request of python without googleapiclient.
I think that in this case, "Method: mediaItems.search" is suitable.
If my understanding is correct, how about this sample script?
Sample script:
Before you use this script, please set the variable of albumId.
from __future__ import print_function
import json
import pickle
import os.path
import requests
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def main():
credentialsFile = 'credentials.json'
pickleFile = 'token.pickle'
SCOPES = ['https://www.googleapis.com/auth/photoslibrary.readonly']
creds = None
if os.path.exists(pickleFile):
with open(pickleFile, 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
credentialsFile, SCOPES)
creds = flow.run_local_server()
with open(pickleFile, 'wb') as token:
pickle.dump(creds, token)
albumId = '###' # <--- Please set the album ID.
url = 'https://photoslibrary.googleapis.com/v1/mediaItems:search'
payload = {'albumId': albumId}
headers = {
'content-type': 'application/json',
'Authorization': 'Bearer ' + creds.token
}
res = requests.post(url, data=json.dumps(payload), headers=headers)
print(res.text)
if __name__ == '__main__':
main()
Note:
In this case, you can use the scope of both https://www.googleapis.com/auth/photoslibrary.readonly and https://www.googleapis.com/auth/photoslibrary.
Reference:
Method: mediaItems.search
I'm using google service account for access all mail from gmail account without UI interface but When I execute my code it giving me error
googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/labels?alt=json returned
"Bad Request">
But when i check Quotas from https://console.developers.google.com/apis/api/gmail.googleapis.com/quotas
there is showing all request that I did using my python code but it always return Bad request when I execute below code.
import httplib2
from apiclient import discovery
from oauth2client.service_account import ServiceAccountCredentials
def get_credentials():
scopes = ['https://mail.google.com/',
'https://www.googleapis.com/auth/gmail.compose',
'https://www.googleapis.com/auth/gmail.metadata',
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/gmail.labels',
'https://www.googleapis.com/auth/gmail.modify',
'https://www.googleapis.com/auth/gmail.metadata',
'https://www.googleapis.com/auth/gmail.settings.basic']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'client_secret.json', scopes=scopes)
return credentials
def main():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('gmail', 'v1', http=http)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
else:
print('Labels:')
for label in labels:
print(label['name'])
if __name__ == '__main__':
main()
Much has changed since this post was first written,
If anyone else is still looking for an answer. This is my initialization process for the Gmail API today.
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/gmail.readonly'
def main():
# Setup for the Gmail API
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))
# Call the Gmail API to fetch INBOX
results = service.users().labels().list().execute()
A major difference is the use of access tokens along with credentials in my code.