Using the Cloudant-Python Library to connect using API Keys - python

I am trying to use the cloudant python library (http://cloudant-labs.github.io/cloudant-python/) in a Flask application but I can't see where you would use API keys to connect to your cloudant account
I tried this:
import cloudant
account = cloudant.Account('account_name')
login = account.login('public_key', 'private_key')
But it doesn't do anything

It looks like you posted this to github. I wanted others to be able to find the answer.
https://github.com/cloudant-labs/cloudant-python/issues/43:
import cloudant
account = cloudant.Account(USERNAME, auth=(API_KEY, API_SECRET))

not cloud ant but raw code
import requests
import json
#basic authentication
auth = ('account', 'private_key')
post_url = "https://account_name.cloudant.com/database".format(auth[0])
r = requests.put(post_url, auth=auth)
print json.dumps(r.json(), indent=1)

Related

Authentification issue to BigQuery API REST using Python

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

how to get id_token in Python Flask OpenID?

I have successfully implemented Keycloak OpenID + Python (v3.6) Flask integration using Flask-oidc.
I use below code to get user info,access_token and refresh_token
oidc = OpenIDConnect(app)
info = oidc.user_getinfo(['preferred_username', 'email', 'sub', 'given_name', 'iss'])
access_token = oidc.get_access_token()
refresh_token = oidc.get_refresh_token()
And got the results as well. But for a reason i need id_token as well. I tried,
oidc.get_cookie_id_token()
(which is already deprecated), but it gave decoded result not encoded token.
Anybody know how to get id_token from flask-oidc ?
I found a solution,
from oauth2client.client import OAuth2Credentials
id_token_jwt = OAuth2Credentials.from_json(oidc.credentials_store[info.get('sub')]).id_token_jwt

googleapi.discovery iam create service account

Hi I want to use the google api service to create service accounts.
Here is my current code:
base_url = f"https://iam.googleapis.com/v1/projects/{project}/serviceAccounts"
auth = f"?access_token={access_token}"
data = {"accountId": name,
"serviceAccount": {
"displayName": name
}}
Create a service Account
r = requests.post(base_url + auth, json=data)
try:
r.raise_for_status()
except requests.HTTPError:
if r.status_code != 409:
raise
This works, but it uses the requests package.
I want to use googleapiclient
from googleapiclient.discovery import build
credentials = GoogleCredentials.get_application_default()
api = build(service, version, credentials=credentials)
Then, where do I find information on how to use this api object?
I've tried:
api.projects().serviceAccounts.create(name=name).execute()
But this does not work, and I don't know how to find what arguments are expected or required.
You can find the GCP IAM API documentation here.
The arguments required and values are documented there.
For anyone else who is struggling.
Check out api explorer to get the format of the request.
For example, If the endpoint is iam.projects.serviceAccounts.get
and you need to provide name = "projects/project/serviceAccounts/sa#gsc.googleserviceaccounts.com"
Then your call will look like:
from googleapiclient.discovery import build
credentials = GoogleCredentials.get_application_default()
api = build(service, version, credentials=credentials)
sa = api.projects().serviceAccounts().get(name="projects/project/serviceAccounts/sa#gsc.googleserviceaccounts.com")
Hope this helps someone.

Using python to connect to Docebo api via Oauth2

This is what I have so far. No real success. Trying to retrieve a token, but nothing seems to work. Just returns a giant mess of characters.
import requests
import json
auth_url = "http://learn.ZZZZZZZ.com/oauth2/authorize"
#credential
auth_client_id = "BBBBBBBBBBBBBBBBBBBBBBBB"
auth_client_secret = "YYYYYYYYYYYYYYYYYYYYY"
payload={'grant_type':'client_credentials', 'client_id':auth_client_id,'client_secret':auth_client_secret}
headers={'Accept':'application/json', 'Content-Type':'application/x-www-form-urlencoded'}
response = requests.post(auth_url,headers=headers,data=payload)
response.text
Use the token endpoint to obtain an access token.
auth_url = "http://learn.ZZZZZZZ.com/oauth2/token"
Docebo API documentation

Getting authenticationerror.login_cookie_required error while using Google adwords API with Python

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

Categories