403 Forbidden error google plus python - python

There are my codes:
import pprint
import httplib2
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
SCOPES = ['https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/plus.stream.write']
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'
CLIENT_ID = "my client id"
CLIENT_SECRET = "my client secret"
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=SCOPES,
redirect_uri=REDIRECT_URI)
auth_uri = flow.step1_get_authorize_url()
print 'Please paste this URL in your browser to authenticate this program.'
print auth_uri
code = raw_input('Enter the code it gives you here: ')
credentials = flow.step2_exchange(code)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('plusDomains', 'v1', http=http)
user_id = 'me'
print('Insert activity')
result = service.activities().insert(
userId = user_id,
body = {
'object' : {
'originalContent' : 'Happy Monday! #caseofthemondays'
},
'access' : {
'items' : [{
'type' : 'domain'
}],
'domainRestricted': True
}
}).execute()
print('result = %s' % pprint.pformat(result))
and there are my error:
Traceback (most recent call last):
File "/home/karl/workspace/googleplus/google_plus/google_plus_pic.py", line 44, in <module>
'domainRestricted': False
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 128, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 680, in execute
raise HttpError(resp, content, uri=self.uri)
apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/plusDomains/v1/people/me/activities?alt=json returned "Forbidden">
I have read a lot of information,but I don't know how to solve the problem.
Where is the bug?

To use the Google+ Domains API, you need to make sure that the Domain for the user you are acting on behalf of has been set up with the right permissions for your app. These instructions are under the "Delegate domain-wide authority to your service account" section of Step 1 of the quick-start guide.
Specifically, you need to associate your app's Client ID with the scopes your app will use in the control panel for the domain. The domain administrator is the only person who can do this--so if you are working with another domain, be sure you get in contact with that person. Also, the scopes listed in the control panel must match EXACTLY with the scopes you request in your app.

Related

Google Sheets API for python2.7 --> "Invalid JSON payload. Root element must be a message"

I've been struggling with this error for a number of weeks now and have tried solutions from previously posted questions relating to the Python API for Google Sheets.
I continuously get an error when I make a "write" request to my spreadsheet through the Google Sheets API for python. The error says that I'm submitting an invalid JSON, but I've tested the JSON structure against the interactive test window (Google APIs Explorer) and the request from there updates my sheet properly.
The code is below
from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
import datetime
import json
# Call the Sheets API
SPREADSHEET_ID = #mySheetID
RANGE_NAME = '2018_Raw Data!A3:A367'
months = { 0:"Jan", 1:"Feb",2:"Mar",4:"Apr",5:"May",6:"Jun",7:"Jul",8:"Aug",9:"Sep",10:"Oct",11:"Nov",12:"Dec"}
now = datetime.datetime.now()
date = str(now.day) +"-"+ months[now.month] + "-"+str(now.year)
day_of_year = now.timetuple().tm_yday
myRow = day_of_year+2
print (date)
print (myRow)
BWRange= '2018_Raw Data!B' + str(myRow)
BFRange= '2018_Raw Data!C' + str(myRow)
myBodyWeight=150
myBF="10%"
print (BWRange)
print (BFRange)
BWData = {}
BWData['values']= [[myBodyWeight]]
BWData['majorDimension']="ROWS"
BWData['range']= BWRange
BWJson= json.dumps(BWData)
BFData = {}
BFData['values']= [[myBF]]
BFData['majorDimension']="ROWS"
BFData['range']= BFRange
BFJson= json.dumps(BFData)
print (BWJson)
print (BFJson)
# Setup the Sheets API
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
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('sheets', 'v4', http=creds.authorize(Http()))
#bw
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWJson)
response = request.execute()
pprint(response)
#bf
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFJson)
response = request.execute()
pprint(response)
Error is below:
Traceback (most recent call last):
File "C:\sheets\mySheets.py", line 65, in <module>
response = request.execute()
File "C:\Python27\lib\site-packages\googleapiclient\_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Python27\lib\site-packages\googleapiclient\http.py", line 842, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1demD8sm5-Jvi7ImHcOu03sHaU7PF61ym1eyvjN1bGfw/values/2018_Raw%20Data%21B234?alt=json&valueInputOption=USER_ENTERED returned "Invalid JSON payload received. Unknown name "": Root element must be a message.">
I've reviewed the following posts below:
Python3 google spreadsheet api batchUpdate Json formatting
Invalid JSON Payload error with python google sheets API
Any help is appreciated - thanks!
I think that your request body is correct. So how about this modification?
From :
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWJson)
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFJson)
To :
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=BWRange, valueInputOption="USER_ENTERED", body=BWData)
request = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID, range=BFRange,valueInputOption="USER_ENTERED", body=BFData)
Note :
In this modification, json.dumps() was removed.
This script supposes that Sheets API is enabled at API console, and your access token can be used for spreadsheets().values().update().
If this didn't work, please tell me. I would like to modify it.

How to create Google Apps Script?

I use service account and it's my code:
test.py
import httplib2
from apiclient import discovery
from googleapiclient.http import MediaFileUpload
from oauth2client.service_account import ServiceAccountCredentials
SCOPE = 'https://www.googleapis.com/auth/drive'
KEY_DICT = {...}
credentials = ServiceAccountCredentials.from_json_keyfile_dict(KEY_DICT, SCOPE)
http = credentials.authorize(httplib2.Http())
drive = discovery.build('drive', 'v3', http=http)
script = discovery.build('script', 'v1', http=http)
file_name = 'test.gs'
file_metadata = {
'name': file_name,
'mimeType': 'application/vnd.google-apps.script'
}
media = MediaFileUpload(file_name, mimetype='text/plain')
file = drive.files().create(body=file_metadata, media_body=media, fields='id').execute()
script_id = file.get('id')
request = {
"function": 'getFoldersUnderRoot',
}
response = script.scripts().run(body=request, scriptId=script_id).execute()
print response['response'].get('result')
test.gs
function getFoldersUnderRoot() {
var root = DriveApp.getRootFolder();
var folders = root.getFolders();
var folderSet = {};
while (folders.hasNext()) {
var folder = folders.next();
folderSet[folder.getId()] = folder.getName();
}
return folderSet;
}
Then I get the following error:
Traceback (most recent call last):
File "./test.py", line 37, in <module>
response = script.scripts().run(body=request, scriptId=script_id).execute()
File "site-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
return wrapped(*args, **kwargs)
File "site-packages/googleapiclient/http.py", line 840, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://script.googleapis.com/v1/scripts/1LI...4y0:run?alt=json returned "Request contains an invalid argument.">
What am I doing wrong? Maybe I should deploy the script? Maybe this works only web UI. I didn't find how to do it via dev console.
Unfortunately there are known issues with using service accounts and the Google App Scripts API. You can read more about this issue here.
The work-around is to user client credentials to generate a refresh token manually, and then use the refresh token as a means of getting an authorization token.

Gmail API Push Notifications gives Error 403

I am trying to get push notifications regarding all the new inbox messages I receive in my email. I have configured the pubsub client as mentioned in the pubsub doc. Following is the code:
import httplib2
from apiclient import discovery
from oauth2client import client as oauth2client
from lib.common.models.main.users import User
from oauth2client.client import SignedJwtAssertionCredentials,\
AccessTokenRefreshError
PUBSUB_SCOPES = ['https://www.googleapis.com/auth/pubsub']
def create_pubsub_client(http=None):
credentials = oauth2client.GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
credentials = credentials.create_scoped(PUBSUB_SCOPES)
if not http:
http = httplib2.Http()
credentials.authorize(http)
return discovery.build('pubsub', 'v1', http=http)
pubsub = create_pubsub_client()
topic = 'projects/<project-name>/topics/<Topic-name>'
policy = {
'policy': {
'bindings': [{
'role': 'roles/pubsub.publisher',
'members': ['serviceAccount:<my-service-account>'],
}],
}
}
resp = pubsub.projects().topics().setIamPolicy(resource=topic, body=policy).execute()
request = {
'labelIds': ['INBOX'],
'topicName': 'projects/<project-name>/topics/<Topic-name>'
}
f = file('link-to.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'service-account-email',
key,
scope='https://mail.google.com/',
)
user = User.query.filter(User.id == 143).first()
accesskey = user.get_access_key(True)
credentials.access_token = accesskey['key']
service = discovery.build('gmail','v1',credentials=credentials)
service.users().watch(userId='me', body=request).execute()
When I run the above Program, I encounter the following error:
Traceback (most recent call last):
File "/home/kmittal/workspace/engine/workers/newPubSubClient.py", line 82, in
service.users().watch(userId='me', body=request).execute()
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 135, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/googleapiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: https://www.googleapis.com/gmail/v1/users/me/watch?alt=json returned "Invalid topicName does not match projects/SOME_ANOTHER_PROJECT/topics/*">
As per this other answer, it looks like you can only create a watch for topics that are part of your own project, not another project. The documentation seems to back this up as it implies you must specify myproject (your own project ID):
The topic name can be any name you choose under your project (i.e.
matching projects/myproject/topics/*, where myproject is the Project
ID listed for your project in the Google Developers Console).

Using Google Picasa API with Python

I have been using Google's Picasa API successfully from last 6 months or so.
Today I have started getting an error
raise GooglePhotosException(e.args[0])
GooglePhotosException: (403, 'Forbidden', 'Authorization required')
I checked my credentials.
self.gd_client = gdata.photos.service.PhotosService()
self.gd_client.email = EmailOfTheUploadingPictureAccount
self.gd_client.password = PasswordOfTheAccount
self.gd_client.source = 'destipak' #Not sure about that
self.feed_url = "/data/feed/api/user/"
self.entry_url = "/data/entry/api/user/"
self.gd_client.ProgrammaticLogin()
Everything was working well since yesterday. Anyone has any clues?
EDIT
Example given on Picasa for python is also not working.
URL
#!/usr/bin/python2.5
import gdata.photos.service
import gdata.media
import gdata.geo
gd_client = gdata.photos.service.PhotosService()
gd_client.email = '=change=' # Set your Picasaweb e-mail address...
gd_client.password = '=change=' # ... and password
gd_client.source = 'api-sample-google-com'
gd_client.ProgrammaticLogin()
albums = gd_client.GetUserFeed()
for album in albums.entry:
print 'Album: %s (%s)' % (album.title.text, album.numphotos.text)
photos = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s?kind=photo' % (album.gphoto_id.text))
for photo in photos.entry:
print ' Photo:', photo.title.text
tags = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=tag' % (album.gphoto_id.text, photo.gphoto_id.text))
for tag in tags.entry:
print ' Tag:', tag.title.text
comments = gd_client.GetFeed('/data/feed/api/user/default/albumid/%s/photoid/%s?kind=comment' % (album.gphoto_id.text, photo.gphoto_id.text))
for comment in comments.entry:
print ' Comment:', comment.content.text
EDIT 2
Full traceback
Traceback (most recent call last):
File "/Users/mac/Picasa_API.py", line 158, in <module>
check_api()
File "/Users/mac/Picasa_API.py", line 140, in check_api
albums = gd_client.GetUserFeed()
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 235, in GetUserFeed
return self.GetFeed(uri, limit=limit)
File "/Users/mac/destipak/env/lib/python2.7/site-packages/gdata/photos/service.py", line 180, in GetFeed
raise GooglePhotosException(e.args[0])
gdata.photos.service.GooglePhotosException: (403, 'Forbidden', 'Authorization required')
Here is the code I use to get OAuth2 authentication working with Picasa. First you need to create a client ID through the Google Developer Console: at https://console.developers.google.com/ and then you must download the client secrets as JSON and pass the filename to OAuth2Login.
The first time you run this code, you will have to authorize the client through your web browser, and paste the code you get there into the application. The credentials are then stored in the file specified by credential_store.
def OAuth2Login(client_secrets, credential_store, email):
scope='https://picasaweb.google.com/data/'
user_agent='myapp'
storage = Storage(credential_store)
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
uri = flow.step1_get_authorize_url()
webbrowser.open(uri)
code = raw_input('Enter the authentication code: ').strip()
credentials = flow.step2_exchange(code)
storage.put(credentials)
if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
http = httplib2.Http()
http = credentials.authorize(http)
credentials.refresh(http)
gd_client = gdata.photos.service.PhotosService(source=user_agent,
email=email,
additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})
return gd_client
I ran into this as well. Seems like email/password authentication has been turned off, and we need to switch to OAuth2. See
https://groups.google.com/forum/#!topic/Google-Picasa-Data-API/4meiAJ40l3E

python dropbox api error

I'm following the tutorial here
So far so good but the upload example give me errors. The code:
from dropbox import client, rest, session
f = open('txt2.txt') # upload a file
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
The error:
Traceback (most recent call last):
File "dropbox_ul.py", line 4, in <module>
response = client.put_file('/magnum-opus.txt', f)
AttributeError: 'module' object has no attribute 'put_file'
Where did I go wrong?
EDIT: The new code I'm trying. This is actually from the dropbox developer website. As I stated earlier, I did go through the authentication and setup:
# Include the Dropbox SDK libraries
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
APP_KEY = 'iqxjea6s7ctxv9j'
APP_SECRET = 'npac0nca3p3ct9f'
# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('txt2.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response
folder_metadata = client.metadata('/')
print "metadata:", folder_metadata
f, metadata = client.get_file_and_metadata('/magnum-opus.txt',rev='362e2029684fe')
out = open('magnum-opus.txt', 'w')
out.write(f)
print(metadata)
and the error:
url: https://www.dropbox.com/1/oauth/authorize?oauth_token=jqbasca63c0a84m
Please authorize in the browser. After you're done, press enter.
linked account: {'referral_link': 'https://www.dropbox.com/referrals/NTMxMzM4NjY5', 'display_name': 'Greg Lorincz', 'uid': 3133866, 'country': 'GB', 'quota_info': {'shared': 78211, 'quota': 28185722880, 'normal': 468671581}, 'email': 'alkopop79#gmail.com'}
Traceback (most recent call last):
File "dropb.py", line 28, in <module>
response = client.put_file('/magnum-opus.txt', f)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/client.py", line 149, in put_file
return RESTClient.PUT(url, file_obj, headers)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 146, in PUT
return cls.request("PUT", url, body=body, headers=headers, raw_response=raw_response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/dropbox-1.4-py2.7.egg/dropbox/rest.py", line 113, in request
raise ErrorResponse(r)
dropbox.rest.ErrorResponse: [403] 'The provided token does not allow this operation'
You haven't initialized the client object. Refer to the tutorial again and you'll see this:
client = client.DropboxClient(sess)
The sess object must also be initialized before calling the client module's DropboxClient method:
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
You should have all the required parameters (i.e., APP_KEY, APP_SECRET, ACCESS_TYPE) assigned to you when you register your application.
I followed the edited code of yours and things worked out perfectly.
from dropbox import client, rest, session
# Get your app key and secret from the Dropbox developer website
app_key = 'enter-your-app_key'
app_secret = 'enter-your-app_secret'
ACCESS_TYPE = 'dropbox'
sess = session.DropboxSession(app_key, app_secret, ACCESS_TYPE )
request_token = sess.obtain_request_token()
# Make the user sign in and authorize this token
url = sess.build_authorize_url(request_token)
print "url:", url
print "Please authorize in the browser. After you're done, press enter."
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
client = client.DropboxClient(sess)
print "linked account:", client.account_info()
f = open('/home/anurag/Documents/sayan.odt')
response = client.put_file('/sayan.odt', f)
print "uploaded:", response
Notice the response and file location on your system, in your code that doesn't matches.
Thanks.

Categories