403 Access Denied Error while creating a dataset in DOMO - api

I'm getting an 404 access denied error while trying to create a dataset in DOMO, anyone who is good in DOMO please help me,
import logging
from pydomo import Domo
from pydomo.datasets import DataSetRequest, Schema, Column, ColumnType, Policy
from pydomo.datasets import PolicyFilter, FilterOperator, PolicyType, Sorting
client_id = ''
client_secret_code = ''
data_set_id = ''
api_host = 'api.domo.com'
domo = Domo(client_id, client_secret_code, logger_name='foo', log_level=logging.INFO,
api_host=api_host)
data_set_name = 'Testing'
data_set_description = 'Test_to_update_schema'
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)
domo = Domo(client_id, client_secret_code, logger_name='foo', log_level=logging.INFO,
api_host=api_host)
dsr = DataSetRequest()
dsr.name = data_set_name
dsr.description = data_set_description
dsr.schema = Schema([Column(ColumnType.STRING, 'Id'),
Column(ColumnType.STRING, 'Publisher_Name')])
dataset = domo.datasets.create(dsr)
print(dataset)

This is Authorization error. Either of credentials are wrong that is client_id, client_secret_code or maybe both.

I have the same error in .NET when using Domo to connect and get data from the dataset. I fix this when I create a base64 string and passed it to auth for example Authorization is Basic
"Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{clientId}:{clientSecret}"))
I am not sure how this goes in Python but create a base64 string and pass for auth.

Related

Getting error in a python script when using QuickSight API calls to retrieve the value of user parameter selection

I am working on a python script which will use QS APIs to retrieve the user parameter selections but keep getting the below error:
parameters = response['Dashboard']['Parameters'] KeyError: 'Parameters'
If I try a different code to retrieve the datasets in my QS account, it works but the Parameters code doesn't. I think I am missing some configuration.
#Code to retrieve the parameters from a QS dashboard (which fails):
import boto3
quicksight = boto3.client('quicksight')
response = quicksight.describe_dashboard(
AwsAccountId='99999999999',
DashboardId='zzz-zzzz-zzzz'
)
parameters = response['Dashboard']['Parameters']
for parameter in parameters:
print(parameter['Name'], ':', parameter['Value'])
#Code to display the datasets in the QS account (which works):
import boto3
import json
account_id = '99999999999'
session = boto3.Session(profile_name='default')
qs_client = session.client('quicksight')
response = qs_client.list_data_sets(AwsAccountId = account_id,MaxResults = 100)
results = response['DataSetSummaries']
while "NextToken" in response.keys():
response = qs_client.list_data_sets(AwsAccountId = account_id,MaxResults = 100,NextToken=response["NextToken"])
results.extend(response["DataSetSummaries"])
for i in results:
x = i['DataSetId']
try:
response = qs_client.describe_data_set(AwsAccountId=account_id,DataSetId=x)
print("succeeded loading: {} for data set {} ".format(x, response['DataSet']['Name']))
except:
print("failed loading: {} ".format(x))

Encrypted access token request to google api failed with 400 code

Recently I come up a scenario where I need to encrypt a WEB API request and response using PyCryptodome inside Synapse notebook activity. I am trying to make a call to Google API, but the request should be encrypted and similarly response should be encrypted. After making the call with encrypted data, I am getting below error.
Error:
error code: 400, message: Invalid JSON Payload received. Unexpected Token, Status: Invalid argument.
I have written below code:-
import os
import requests
import json
import base64
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.padding import pad,unpad
import secrets
key= os.urandom(16)
iv = Random.new().read(AES.block_size)
def encrypt_data(key, data):
BS = AES.block_size
pad = lambda s: s + ((BS - len(s) % BS) * chr(BS - len(s) % BS)).encode()
cipher = AES.new(key, AES.MODE_CBC, iv)
encrypted_data = base64.b64encode(cipher.encrypt(pad(data)))
return encrypted_data
url = "https://accounts.google.com/o/oauth2/token"
client_Id = "XXXXX"
client_secret = "YYYYY"
grant_type = "refresh_token"
refresh_token = "ZZZZZZ"
access_type="offline"
data = {"grant_type":grant_type,
"client_id":client_Id,
"client_secret":client_secret,
"refresh_token":refresh_token,
"access_type":access_type
}
encode_data = json.dumps(data).encode("utf-8")
encrypt_data = encrypt_data(key,encode_data)
response = requests.post(url, data = encrypt_data)
print(response.content)
It would be really helpful if someone can give me idea or guide me on how I can achieve this.
Thank You!

How to perform a SQL query with SQLAlchemy to later pass it into a pandas dataframe

I have followed this article set up, it all seems to work properly, but I would like now to perform a SQL query and pass the result into a pandas data frame, how could I proceed?
This is what I have now;
host_server = os.environ.get('host_server', 'localhost')
db_server_port = urllib.parse.quote_plus(str(os.environ.get('db_server_port', '5432')))
database_name = os.environ.get('database_name', 'my_data_base123')
db_username = urllib.parse.quote_plus(str(os.environ.get('db_username', 'my_user_name123')))
db_password = urllib.parse.quote_plus(str(os.environ.get('db_password', 'my_password123')))
ssl_mode = urllib.parse.quote_plus(str(os.environ.get('ssl_mode','prefer')))
DATABASE_URL = 'postgresql://{}:{}#{}:{}/{}?sslmode={}'.format(db_username, db_password, host_server, db_server_port, database_name, ssl_mode)
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
engine = sqlalchemy.create_engine(
DATABASE_URL, pool_size=3, max_overflow=0
)
metadata.create_all(database)
app = FastAPI(title="REST API using FastAPI PostgreSQL Async EndPoints")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
#app.on_event("startup")
async def startup():
await database.connect()
#app.on_event("shutdown")
async def shutdown():
await database.disconnect()
Trying to access the database with a SQL query:
with engine.connect() as conn:
result = conn.execute(text("select 'hello world'))
print(result.all())
as it says in the sqlalchemy documentation , but i get some errors, like:
print(result.all())
AttributeError: 'ResultProxy' object has no attribute 'all'
even if i try to access the tables of my database
with engine.connect() as conn:
result = conn.execute(text("select * FROM users"))
print(result.all())
i get the same error
It is solved, I had to upgrade SQLAlchemy
sudo pip install sqlalchemy --upgrade

Google people API returning empty / no results in Python

I'm trying to read contacts from my person gmail account and the instructions provided by Google from the People API is returning an empty list. I'm not sure why. I've tried another solution from a few years ago, but that doens't seem to work. I've pasted my code below. Any help troubleshooting this is appreciated!
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']
from google.oauth2 import service_account
SERVICE_ACCOUNT_FILE = '<path name hidden>.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
def main():
#Shows basic usage of the People API.
#Prints the name of the first 10 connections.
creds = None
service = build('people', 'v1', credentials=credentials)
# Call the People API
print('List 10 connection names')
results = service.people().connections().list(
resourceName='people/me',
pageSize=10,
personFields='names,emailAddresses').execute()
connections = results.get('connections', [])
request = service.people().searchContacts(pageSize=10, query="A", readMask="names")
results = service.people().connections().list(resourceName='people/me',personFields='names,emailAddresses',fields='connections,totalItems,nextSyncToken').execute()
for i in results:
print ('result', i)
for person in connections:
names = person.get('names', [])
if names:
name = names[0].get('displayName')
print(name)
if __name__ == '__main__':
main()

OAuth2 Grant Type - authorization code (python)

I am try to figure out how to get Oauth 2 working in my python code.
import requests, json
import webbrowser
authorize_url = "https://tcfhirsandbox.com.au/oauth2/authorize"
token_url = "https://tcfhirsandbox.com.au/oauth2/token"
state = 'asdasdasdasdasdas'
scope = 'noscope'
callback_uri = "x-argonaut-app://HealthProviderLogin/"
test_api_url = "https://tcfhirsandbox.com.au/fhir/dstu2/Patient?identifier=RN000000200"
client_id = '6A605kYem9GmG38Vo6TTzh8IFnjWHZWtRn46K1hoxQ'
client_secret = 'POrisHrcdMvUKmaR6Cea0b8jtx-z4ewVWrnaIXASO-H3tB3g5MgPV7Vqty7OP8aEbSGENWRMkeVKZDdG7Pw'
authorization_redirect_url = authorize_url + '?response_type=code&state=' + state + '&client_id=' + client_id + '&scope='+scope+'&redirect_uri=' + callback_uri
webbrowser.open(authorization_redirect_url)
authorization_code = input("Code:")
data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_uri}
access_token_response = requests.post(token_url, data=data, verify=True, allow_redirects=True, auth=(client_id, client_secret))
tokens = json.loads(access_token_response.text)
access_token = tokens['access_token']
api_call_headers = {'Authorization': 'Bearer ' + access_token}
api_call_response = requests.get(test_api_url, headers=api_call_headers, verify=True)
print(api_call_response.status_code)
print (api_call_response.text)
The issue here is I have to manually input the code from the authorization URL. I want to automate it !
Thanks,
22/01/2021|09:54AM
Tried this
import requests, json
rom bs4 import BeautifulSoup
import mechanize
authorize_url = "https://tcfhirsandbox.com.au/oauth2/authorize"
token_url = "https://tcfhirsandbox.com.au/oauth2/token"
state = 'asdasdasdasdasdas'
scope = 'noscope'
callback_uri = "x-argonaut-app://HealthProviderLogin/"
test_api_url = "https://tcfhirsandbox.com.au/fhir/dstu2/Patient?identifier=RN000000200"
client_id = '6A605kYem9GmG38Vo6TTzh8IFnjWHZWtRn46K1hoxQ'
client_secret = 'POrisHrcdMvUKmaR6Cea0b8jtx-z4ewVWrnaIXASO-H3tB3g5MgPV7Vqty7OP8aEbSGENWRMkeVKZDdG7Pw'
OAuth_url = authorize_url + '?response_type=code&state=' + state + '&client_id=' + client_id + '&scope='+scope+'&redirect_uri=' + callback_uri
br = mechanize.Browser()
br.open(OAuth_url)
br.select_form(nr=0)
br.form['Username'] = 'my_username'
br.form['Password'] = 'my_password'
r = br.submit()
#print(r.read())
resp = r.read()
br.select_form(nr=0)
ac = br.form.click(name = 'Accept')
soup = BeautifulSoup(resp)
print(soup)
print(ac)
auth_code = str(ac)
code_list = auth_code.split("=")
cd_lst = code_list[1].split("&")
authorization_code = str(cd_lst[0])
print(authorization_code)
data = {'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': callback_uri}
access_token_response = requests.post(token_url, data=data, verify=True, allow_redirects=True, auth=(client_id, client_secret))
print(access_token_response.status_code)
tokens = json.loads(access_token_response.text)
access_token = tokens['access_token']
print(access_token)
I think I am close but still couldn't get it working.
It is giving bad request (error code:400) as response.
If anyone can help with this would be awesome. Thanks
TL;DR You're getting a 400 BAD_REQUEST because the OAuth_url isn't properly constructed. Try:
https://tcfhirsandbox.com.au/oauth2/authorize?
response_type=code&
state=asdasdasdasdasdas&client_id=6A605kYem9GmG38Vo6TTzh8IFnjWHZWtRn46K1hoxQ&
redirect_uri=x-argonaut-app://HealthProviderLogin/
scope=launch%2Fpatient+openid+fhirUser+patient%2F%2A.read&
aud=https://tcfhirsandbox.com.au/
The base url for the reference server you gave (https://tcfhirsandbox.com.au) doesn't resolve.
So I'll demonstrate using another reference server.
CapabilityStatement: https://inferno.healthit.gov/reference-server/r4/metadata?_format=json
SMART Configuration: https://inferno.healthit.gov/reference-server/r4/.well-known/smart-configuration.json
The OAuth_url you've constructed:
https://tcfhirsandbox.com.au/oauth2/authorize?
response_type=code&
state=asdasdasdasdasdas&client_id=6A605kYem9GmG38Vo6TTzh8IFnjWHZWtRn46K1hoxQ&
redirect_uri=x-argonaut-app://HealthProviderLogin/
scope=noscope&
A working OAuth_url with the reference server [^1]:
https://inferno.healthit.gov/reference-server/oauth/authorization?
response_type=code&
state=ad6458f9-240a-42b7-b314-05d0c3b2c7c9&
client_id=SAMPLE_CONFIDENTIAL_CLIENT_ID&
redirect_uri=https%3A%2F%2Finferno.healthit.gov%2Finferno%2Foauth2%2Fstatic%2F
redirect&
scope=launch%2Fpatient+openid+fhirUser+patient%2F%2A.read&
aud=https%3A%2F%2Finferno.healthit.gov%2Freference-server%2Fr4
You'll see two differences between the request you've constructed and reference, one of which is likely causing the 400 BAD_REQUEST:
scope (noscope isn't a valid SMART on FHIR scope [^2], which will cause most servers to error)
aud (you didn't include an aud query param, which is used as a claim in the access_token jwt you'll be issued)
[^1] Constructed using the Inferno test: https://inferno.healthit.gov/inferno/5g6OuEGN4hM/test_sets/test_procedure/
[^2] Direct link to supported SMART on FHIR scopes: http://hl7.org/fhir/smart-app-launch/scopes-and-launch-context/index.html#quick-start