I have a problem working with python-quickbooks package, I try to follow the docs: https://pypi.org/project/python-quickbooks/
Here is my code:
from django.conf import settings
from intuitlib.client import AuthClient
from quickbooks import QuickBooks
from quickbooks.objects.account import Account
auth_client = AuthClient(
client_id=settings.QUICKBOOKS_CLIENT_ID,
client_secret=settings.QUICKBOOKS_CLIENT_SECRET,
environment='sandbox',
redirect_uri=settings.QUICKBOOKS_REDIRECT_URI,
)
client = QuickBooks(
auth_client=auth_client,
refresh_token=settings.QUICKBOOKS_REFRESH_TOKEN,
company_id=settings.QUICKBOOKS_REALM_ID
)
account = Account()
account.from_json(
{
"AccountType": "Accounts Receivable",
"Name": "MyJobs"
}
)
account.save(qb=client)
However, this results in error:
What am I doing wrong here?
You have to provide ACCESS_TOKEN in AuthClient.
In order to get an access token, you have to pass authorization. You can check details about the authorization process here https://developer.intuit.com/app/developer/qbo/docs/develop/authentication-and-authorization/oauth-2.0-playground
Also here is a repo with an example of how to use AuthClient: https://github.com/IntuitDeveloper/SampleOAuth2_UsingPythonClient
from intuitlib.client import AuthClient
from quickbooks.client import QuickBooks, Environments
auth_client = AuthClient(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, Environments.SANDBOX, ACCESS_TOKEN)
qbo_client = QuickBooks(
auth_client=auth_client,
refresh_token=REFRESH_TOKEN,
company_id=REALM_ID,
)
Related
I want to access AWS AppSync API using Python code and confused with requests library.
Auth mode is Cognito user pool. My questions are:
How to get access tokens from Cognito user pool?
How to make queries, mutations, and handle subscriptions?
I tried to do it with auth mode API key. but I am getting the following error.
import requests
import json
URL = "https://vtcarmq7zzeadnkwzcgfr24irm.appsync-api.us-east-1.amazonaws.com/graphql"
headers = {"x-api-key":"da2-bwuyzqchhfgyxemcmdinjegb7e"}
data = json.dumps({
"query": '''
listTodos(filter:{
title:{
contains:"g"
}
} ) {
items{
id title duedate
}
}
'''
} )
r = requests.request("POST", URL , data = data , headers = headers)
print(r.text)
{ "errors" : [ {
"message" : "Unable to parse GraphQL query.",
"errorType" : "MalformedHttpRequestException" } ] }
I have seen this video https://www.youtube.com/watch?v=2U4RsbFO4bA&t=1172s
In this video, for authentication using cognito user pool, he says to make a call to cognito user pool and get the tokens and pass it to aws appsync in headers.
I am new to aws and python request module, trying to write python code for this video.
graphql-python/gql supports AWS AppSync since version 3.0.0rc0.
It supports queries, mutation and even subscriptions on the realtime endpoint.
It supports IAM, api key and JWT authentication methods.
The documentation is available here
Here is an example of a mutation using the API Key authentication:
import asyncio
import os
import sys
from urllib.parse import urlparse
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport
from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
# Uncomment the following lines to enable debug output
# import logging
# logging.basicConfig(level=logging.DEBUG)
async def main():
# Should look like:
# https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.REGION.amazonaws.com/graphql
url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")
api_key = os.environ.get("AWS_GRAPHQL_API_KEY")
if url is None or api_key is None:
print("Missing environment variables")
sys.exit()
# Extract host from url
host = str(urlparse(url).netloc)
auth = AppSyncApiKeyAuthentication(host=host, api_key=api_key)
transport = AIOHTTPTransport(url=url, auth=auth)
async with Client(
transport=transport, fetch_schema_from_transport=False,
) as session:
query = gql(
"""
mutation createMessage($message: String!) {
createMessage(input: {message: $message}) {
id
message
createdAt
}
}"""
)
variable_values = {"message": "Hello world!"}
result = await session.execute(query, variable_values=variable_values)
print(result)
asyncio.run(main())
So I have been using powershell for quite a while now and am somewhat familiar with getting a token from an Azure application using MS Graph configured with application API permissions. I am now attempting to perform the same in a python console application and am getting flummoxed as I constantly get a 400 error. here's the snippet of my code...
import requests
import json
app_id='<appid>'
client_secret='<client secret>'
token_url='https://login.microsoftonline.com/<tenant id>/oauth2 /v2.0/token'
token_data = {
'grant_type': 'client_credentials',
'client_id': app_id,
'client_secret': client_secret,
'resource': 'https://graph.microsoft.com',
'scope':'https://graph.microsoft.com/.default'
}
headers = {'content-type':'application/json'}
token_r = requests.post(token_url, json=token_data)
token = token_r.json().get('access_token')
any ideas?
Figured it out. I needed to add the oAuth2 requests library. See sample code below:
import requests
import json
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient
app_id='<app id>'
client_secret='<client Secret>'
token_url='https://login.microsoftonline.com/tennantname.onmicrosoft.com/oauth2/v2.0/token'
scope='https://graph.microsoft.com/.default'
client = BackendApplicationClient(client_id=app_id, scope=scope, grant_type="client_credentials")
session = OAuth2Session(client=client, scope=scope)
# fill access token
token = session.fetch_token(token_url=token_url,client_id=app_id,scope=scope,client_secret=client_secret)
from azure.monitor import MonitorClient
#from azure.mgmt.monitor import MonitorMgmtClient
from azure.mgmt.monitor import MonitorManagementClient
from azure.common.credentials import UserPassCredentials
import datetime
# Replace this with your subscription id
subscription_id = '************'
# See above for details on creating different types of AAD credentials
credentials = UserPassCredentials(
'****', # Your user
'****', # Your password
)
client = MonitorClient(
credentials,
subscription_id
)
monitor_mgmt_client = MonitorManagementClient(
credentials,
subscription_id
)
after running this code its giving error:
raise error
msrest.exceptions.AuthenticationError: , InvalidClientIdError: (invalid_request) AADSTS900144: The request body must contain the following parameter: 'client_id'
It seems you should not use UserPassCredentials anymore, it has been deprecated.
See this link:
In previous version of the SDK, ADAL was not yet available and we provided a UserPassCredentials class. This is considered deprecated and should not be used anymore.
For Authenticate with token credentials, you could try the code below.
from azure.common.credentials import ServicePrincipalCredentials
# Tenant ID for your Azure Subscription
TENANT_ID = 'ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL'
# Your Service Principal App ID
CLIENT = 'a2ab11af-01aa-4759-8345-7803287dbd39'
# Your Service Principal Password
KEY = 'password'
credentials = ServicePrincipalCredentials(
client_id = CLIENT,
secret = KEY,
tenant = TENANT_ID
)
If you need more control, it is recommended to use ADAL and the SDK ADAL wrapper.
import adal
from msrestazure.azure_active_directory import AdalAuthentication
from msrestazure.azure_cloud import AZURE_PUBLIC_CLOUD
# Tenant ID for your Azure Subscription
TENANT_ID = 'ABCDEFGH-1234-1234-1234-ABCDEFGHIJKL'
# Your Service Principal App ID
CLIENT = 'a2ab11af-01aa-4759-8345-7803287dbd39'
# Your Service Principal Password
KEY = 'password'
LOGIN_ENDPOINT = AZURE_PUBLIC_CLOUD.endpoints.active_directory
RESOURCE = AZURE_PUBLIC_CLOUD.endpoints.active_directory_resource_id
context = adal.AuthenticationContext(LOGIN_ENDPOINT + '/' + TENANT_ID)
credentials = AdalAuthentication(
context.acquire_token_with_client_credentials,
RESOURCE,
CLIENT,
KEY
)
For more details, you could refer to this link : Authenticate with the Azure Management Libraries for Python.
If you don't have an AD App, follow this link to create it. To get the client id(client id is the same with application id) and key, follow this link.
I am having issues trying to create a calendar event using the Google Calendar API with an AWS Lambda function call.
The AWS CloudWatch logs are not giving me a whole lot of information to work with for debugging. I am very new to working with the Google API and can't figure out what is going wrong with my code.
The code I am using is here:
from __future__ import print_function
from oauth2client import service_account
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
import httplib2
import boto3
import json
import logging
import requests
def lambda_handler(event, context):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ses = boto3.client('ses')
email_address = 'myemail#gmail.com' # change it to your email address
SCOPES = ['https://www.googleapis.com/auth/calendar']
SERVICE_ACCOUNT_FILE = 'aws-iot-f3edea2d0394.json'
credentials = service_account.ServiceAccountCredentials.from_json_keyfile_name(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
http = httplib2.Http()
http = credentials.authorize(http)
service = discovery.build('calendar', 'v3', http=http)
calendarId = 'myemail#gmail.com'
event = {
"summary": "aws iot test",
"location": "etc",
"description": "aws iot test - pushed from button",
"start": {
"dateTime": "2018-01-31T09:00:00-07:00",
"timeZone": "America/Los_Angeles"
},
"end": {
"dateTime": "2018-01-31T17:00:00-07:00",
"timeZone": "America/Los_Angeles"
}
}
event = service.events().insert(calendarId='primary', body=event).execute()
The calendar event is not being created, and I cannot figure out why. The only information I am getting from the AWS CloudWatch logs has the last event here:
[INFO] 2018-01-23T17:09:28.116Z 29b2e36a-0060-11e8-8c9e-1725945b009e URL being requested: POST https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json
This is not very informative. Can anyone help out with maybe getting AWS to give me more information, or perhaps point out what I am doing wrong in the Python code? Thank you!
I was able to figure out the issue. Google left out some administrative details needed for the integration to work, and I was able to track down a similar issue someone else was having at Google Calendar Api v3 asp.net Code 200, yet no event inserted.
Turns out you need to enable the Google service account to make changes to your calendar.
I am using the Spotipy python library to interact with the Spotify web api. I have worked through the API and docs but I do not see a clear example that shows how the library supports the Authorization code flow ( https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow ).
I implemented a simple Authorization Code flow with the help of Spotipy. Maybe this is helpful for other people as well. Also on github: https://github.com/perelin/spotipy_oauth_demo
Here is the code:
from bottle import route, run, request
import spotipy
from spotipy import oauth2
PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'your_client_id'
SPOTIPY_CLIENT_SECRET = 'your_client_secret'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'user-library-read'
CACHE = '.spotipyoauthcache'
sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=CACHE )
#route('/')
def index():
access_token = ""
token_info = sp_oauth.get_cached_token()
if token_info:
print "Found cached token!"
access_token = token_info['access_token']
else:
url = request.url
code = sp_oauth.parse_response_code(url)
if code:
print "Found Spotify auth code in Request URL! Trying to get valid access token..."
token_info = sp_oauth.get_access_token(code)
access_token = token_info['access_token']
if access_token:
print "Access token available! Trying to get user information..."
sp = spotipy.Spotify(access_token)
results = sp.current_user()
return results
else:
return htmlForLoginButton()
def htmlForLoginButton():
auth_url = getSPOauthURI()
htmlLoginButton = "<a href='" + auth_url + "'>Login to Spotify</a>"
return htmlLoginButton
def getSPOauthURI():
auth_url = sp_oauth.get_authorize_url()
return auth_url
run(host='', port=8080)
If someone needs the working code here is my current.
Just remember to change the client_id, etc. I put them in config.py.
import spotipy
import spotipy.util as util
from config import CLIENT_ID, CLIENT_SECRET, PLAY_LIST, USER
import random
token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
cache_token = token.get_access_token()
spotify = spotipy.Spotify(cache_token)
results1 = spotify.user_playlist_tracks(USER, PLAY_LIST, limit=100, offset=0)
When I was trying to do this none of these answers really got me there unfortunately. When I ended up figuring it out I detailed how in this post: https://stackoverflow.com/a/42443878/2963703
I was using Django as my backend but all the spotify api oauth stuff is done in javascript so it should still be very useful for you.
The Spotipy library supports the Authorization Code flow, as documented here. For more information, you could also check out Spotipy's oAuth2 module and Util module.