I want to use server-side communication with the Google+ API to retrieve the current user's profile information. I log in the user according to the Google example for python:
credentials = client.credentials_from_clientsecrets_and_code(
CLIENT_SECRET_FILE,
['https://www.googleapis.com/auth/drive.appdata', 'profile', 'email'],
code)
Then I call the Google+ API:
http_auth = credentials.authorize(httplib2.Http())
service = build('plus', 'v1', http = http_auth)
google_request = service.people().list(userId = 'me', collection = 'visible')
result = google_request.execute()
This thows the following error:
HttpAccessTokenRefreshError: invalid_grant
Does anyone have an idea what I can do about this?
I solved the problem by using the correct method people().get() instead of people().list()
At first I wanted to delete the question because the topic seems silly but I copy-pasted the wrong API call from a code sample on Github and therefore I can imagine that others run into this issue as well.
Related
I am migrating my code from ADAL to msal library. I have done all the necessary changes .
Trying to get access token by using the following code:
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential=config["secret"] )
result = None
result = app.acquire_token_silent(config["scope"], account=None)
if not result:
result = app.acquire_token_for_client(scopes=config["scope"])
#With this code i am getting the (access token) but when using
headers = self.get_headers()
request = requests.get(url=folder_path, headers=headers, data={})
getting request response [401enter code here].
I cannot access any resource in the _api/web/lists/... api. SharePoint is a bit odd having multiple APIs to get data (Graph endpoint and _api endpoint), but before I dive into an MSAL conversion I wanted to know whether it actually supports access tokens to this SharePoint _api. I have tried without success. I cannot find anything in the Microsoft documentation about the supported APIs so I was hoping for some guidance. Note our application is currently working with ADAL. Thanks!
I would like to make a HTTP call to this resource :
https://bigquery.googleapis.com/bigquery/v2/projects/{projectId}/jobs
As I read to the documentation I use an API key generated from my GCP project to be authenticated. So with requests I make a simple call like this:
import requests
params = {'key': 'MY_API_KEY'}
base_url = 'https://bigquery.googleapis.com'
project_id = 'MY_PROJECT_ID'
r = requests.get(f'{base_url}/bigquery/v2/projects/{project_id}/jobs', params=params)
Unfortunately it returns a response 401 and I can't figure out why.
Thanks a lot and have a nice day !
Update code after guillaume blaquiere reply :
from google.auth.transport.requests import AuthorizedSession
from google.oauth2 import service_account
base_url = 'https://bigquery.googleapis.com'
project_id = 'project_id'
credentials = service_account.Credentials.from_service_account_file(
'service_account.json',
scopes=['https://www.googleapis.com/auth/bigquery',
'https://www.googleapis.com/auth/cloud-platform'],
)
authed_session = AuthorizedSession(credentials)
response = authed_session.request('GET', f'{base_url}/bigquery/v2/projects/{project_id}/jobs')
print(response.json())
# this returns : {'etag': 'tAZvk1k2f2GY8yHaQF7how==', 'kind': 'bigquery#jobList'}
The API Key no longer works for a large number of Google API. Only some legacy continue to accept an API key.
Now, you need an authenticated request. You can find exemple in the google-auth python library documentation. Look at Refresh and Authorized_session.
Don't hesitate to comment if you need help about the credential obtention, I can also help you on this.
EDIT
When you perform the request, it's, by default, only on the current user. In your case, it's the service account when you use the Python code, and your User account when you use the API Explorer (the swagger like in the Google Documentation).
In your case, I guess that your service account has never performed a job (query or load job) and thus, there is no entry for it.
According with the documentation, is you want to see all the user jobs, you have to add the param ?allUsers=true at the end of your URL
response = authed_session.request('GET', f'{base_url}/bigquery/v2/projects/{project_id}/jobs?allUsers=true')
I want to use python and the verification site api (v1) to verify website in my webmaster tools. In this example I want to get all verified sites using the verification api, because that function doesn't have parameters. (I know that it's possible via the webmaster tools, as well)
#!/usr/bin/python
import httplib2
from apiclient import errors
from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
http = httplib2.Http()
storage = Storage('credentials')
storage_verify = Storage('credentials_verify')
credentials = storage.get()
credentials_verify = storage_verify.get()
http_wm = credentials.authorize(http)
http_sv = credentials_verify.authorize(http)
webmasters_service = build('webmasters', 'v3', http=http_wm)
verification_service = build('siteVerification', 'v1', http=http_sv)
site_list = webmasters_service.sites().list().execute()
print(site_list)
# this line generates the error
verified_site_list = verification_service.webResource().list().execute()
print(verified_site_list)
There is an insufficient permission error:
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/siteVerification/v1/webResource?alt=json returned "Insufficient Permission">
I have read and write access for the siteVerification api (I've checked my token here: https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=TOKEN )
Any ideas what I'm doing wrong or how I can debug the code?
Make sure you read and understand https://developers.google.com/site-verification/v1/invoking in its entirety. Especially you need to appreciate:
Verify a new site
To verify a site,
- First request a verification token by calling getToken.
- Place the token on your site using whatever method you choose.
- Ask Google to verify that the site is yours, using the insert operation.
All you need to do is properly construct two requests, getToken and insert. What "properly" means, is discussed in all detail in the docs I linked above.
If you really need help with code, you need to show a minimal working example so that we can reproduce the error you retrieve.
I found my problem...
These two lines:
http_wm = credentials.authorize(http)
http_sv = credentials_verify.authorize(http)
uses the same http object which isn't allowed.
I use this code now:
http_wm = httplib2.Http()
http_sv = httplib2.Http()
http_wm = credentials.authorize(http_wm)
http_sv = credentials_verify.authorize(http_sv)
I'm trying to make authorized requests to the google spreadsheets API and all the examples I found requests email and password from the user.
http://www.payne.org/index.php/Reading_Google_Spreadsheets_in_Python
http://www.mattcutts.com/blog/write-google-spreadsheet-from-python/
http://mrwoof.tumblr.com/post/1004514567/using-google-python-api-to-get-rows-from-a-google
Well this problem was solved with OAuth2 protocol which Google implements. I've gone through the OAuth2 process and I have a valid access_token, which I use to interact with Google Drive smoothly:
access_token = get_access_token() # external function
user_agent = request.META['HTTP_USER_AGENT']
credentials = AccessTokenCredentials(access_token, user_agent)
http = httplib2.Http()
http = credentials.authorize(http)
service = build('drive', 'v2', http)
service.files().copy(fileId=k, body=dict(title="Copia")).execute() # this works!
But I can't figure out a way to use the access_token to interact with the spreadsheets API. Does it still uses email and password login?
Thanks!
PS: BTW, I'm using the python gdata package, and please let me know if you have a good reference for it! :)
So, if you already have an access token (maybe you got it by your own via Oauth2 protocol, like me). You can interact with google spreadsheet api passing an instance of AuthSubToken to methods of SpreadsheetsClient.
from gdata.gauth import AuthSubToken
from gdata.spreadsheets.client import SpreadsheetsClient
atok = AuthSubToken(token_string=get_access_token()) # acess token via protocol
data = SpreadsheetsClient().get_worksheets(key, auth_token=atok)
I am trying to use python to consume some adwords soap API, I am able to get the auth token but when I try to make a get request I got the authenticationerror.login_cookie_required error. Any ideas?
from suds.client import Client
auth_data = {'accountType':'GOOGLE', 'Email':'xxx#xxx.com', 'Passwd':'xxxxxxxx', 'service':'adwords', 'source':'xxxxxxxxxx'}
auth_data = urllib.urlencode(auth_data)
auth_request = urllib2.Request('https://www.google.com/accounts/ClientLogin', auth_data)
auth_response = urllib2.urlopen(auth_request)
auth_response = auth_response.read()
split = auth_response.split('=')
auth_token = split[len(split)-1]
url = 'https://adwords-sandbox.google.com/api/adwords/cm/v201109/CampaignService?wsdl'
client = Client(url)
authToken = auth_token
developerToken = 'xxx#xxx.com++NZD'
userAgent = 'jameslin-python'
client.set_options(soapheaders=(authToken,developerToken,userAgent))
client.service.get()
Have you tried using the Python client library for the AdWords API?
http://code.google.com/p/google-api-ads-python/
authToken isn't a SOAP header. RequestHeader is the soap header and authToken is a member of that header. See http://code.google.com/apis/adwords/docs/headers.html and http://code.google.com/apis/adwords/docs/#soap for more details.
I also wish to point out that AdWords API official forum is http://groups.google.com/group/adwords-api, where we regularly answer questions on AdWords API. If you have any followup questions, feel free to ask on the official forum.
Cheers,
Anash