Python: QuickBooks API integration - python

Good afternoon,
I've spent the better part of today trying to export the P&L from my QBO sandbox company into a python dataframe (or at least a dictionary). I've been following the instructions here but cannot for the life of me get the authentication to work.
I've been using the OAuth playground to generate my authorization token, and have the code below:
from intuitlib.client import AuthClient
from intuitlib.enums import Scopes
import csv
reader = csv.DictReader(open("/home/mike/home_health/quickbooks_details.csv"))
credentials = next(reader)
auth_client = AuthClient(
client_id=credentials.get('client_id'),
client_secret=credentials.get('secret'),
redirect_uri='https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl',
environment='sandbox')
auth_client.get_bearer_token(auth_code='MY_AUTH_CODE', realm_id='MY_REALM_ID')
from quickbooks import QuickBooks
client = QuickBooks(
auth_client=auth_client,
refresh_token=auth_client.refresh_token,
company_id=credentials.get('company_id'),
)
client.get_report(report_type='ProfitAndLoss')
Try as I might, I keep getting the following error:
AuthorizationException: QB Auth Exception: Application authentication failed
{"warnings":null,"intuitObject":null,"fault":{"error":[{"message":"message=DispatcherError; errorCode=003100; statusCode=401","detail":"","code":"3100","element":null}],"type":"AUTHENTICATION"},"report":null,"queryResponse":null,"batchItemResponse":[],"attachableResponse":[],"syncErrorResponse":null,"requestId":null,"time":1617720333515,"status":null,"cdcresponse":[]}
Any help would be hugely appreciated!
Thanks!

Everything seems right, just am not sure what value you have put for company_id. For the company_id variable in client set it's value as the Realm Id that you have and try running it. This works for me
from intuitlib.client import AuthClient
from quickbooks import QuickBooks
import os
auth_client = AuthClient(
client_id=os.getenv('CLIENT_ID'),
client_secret=os.getenv('CLIENT_SECRET'),
access_token=os.getenv('ACCESS_TOKEN'),
environment='sandbox',
redirect_uri='https://developer.intuit.com/v2/OAuth2Playground/RedirectUrl',
)
client = QuickBooks(
auth_client=auth_client,
refresh_token=os.getenv('REFRESH_TOKEN'),
company_id=os.getenv('REALM_ID'),
)
client.get_report(report_type='ProfitAndLoss')

Related

SalesforceExpiredSession Error using simple_salesforce package in Python

I am trying to download a report I created on SalesForce using simple_salesforce package in python.
Below is the sample code:
from simple_salesforce import Salesforce
import requests
import pandas as pd
from io import StringIO
sf = Salesforce(username='myusername',
password='mypassword',
security_token='mytoken',
version='46.0')
report_id = 'myreportid'
sf.restful('analytics/reports/{}'.format(report_id))
However, this chunk of code yields the following error:
SalesforceExpiredSession: Expired session for https://company_name.my.salesforce.com/services/data/v46.0/analytics/reports/myreporid. Response content: [{'message': 'This session is not valid for use with the REST API', 'errorCode': 'INVALID_SESSION_ID'}]
(continuing from comments)
My bad, typo. Does your Profile have "API Enabled" checkbox ticked?
And you said you can see success in login history, active session?
What happens when you try to do same thing manually with workbench. Login, then in top menu Utilities -> REST Explorer should let you run your report.
Maybe simple is creating a SOAP session id which for whatever reason is incompatible with REST API (to be fair I thought they were pretty interchangeable, maybe your company disabled REST API, I heard it's possible to request that from SF support...)
If workbench works - you may have to login in simple different way, creating "connected app" and reading up about https://help.salesforce.com/s/articleView?id=remoteaccess_oauth_username_password_flow.htm&type=5&language=en_US for example

Is it possible to get changesets created between a specific date using TFSAPI?

I'm writing a program to find changesets based on created date using Microsoft TFS Python Library (TFS API Python client).
I read through the documentation and found that the get_changesets() method can be used for this. But there are no arguments that can help filter out the changesets based on date.
On further reading, I found that get_tfs_resource() could be used, but being new to using APIs, I cannot figure out how to set payload for the method call, that would help me to filter out the changesets using date.
Can someone help me out with the correct methods to be used, or the payload that can be sent as specified?
You can use the TFS Rest API get get changeset and do this
https://{instance}/{collection}/{project}/_apis/tfvc/changesets?searchCriteria.fromDate=2020-03-11&searchCriteria.toDate=2020-03-12&api-version=4.1
You may check the code below:
from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication
import pprint
# Fill in with your personal access token and org URL
personal_access_token = 'YOURPAT'
organization_url = 'https://dev.azure.com/YOURORG'
# Create a connection to the org
credentials = BasicAuthentication('', personal_access_token)
connection = Connection(base_url=organization_url, creds=credentials)
tfsv_client = connection.clients.get_tfvc_client()
project_name="myprojname"
search_criteria = type('',(object,),{"item_path":'$/myprojname/Trunk/Main',"fromDate":'01-01-2019', "toDate":'11-13-2019-2:00PM'})
changeset_info = tfvcclient.get_changesets(project=project_name,search_criteria=search_criteria)
Reference from:
https://github.com/microsoft/azure-devops-python-api
https://github.com/microsoft/azure-devops-python-api/blob/dev/azure-devops/azure/devops/v5_1/tfvc/tfvc_client.py
How to access azure Dev Ops data such as Changeset between dates using python?

How can I get the number of undelivered messages (metric api) present in Pubsub using python client library?

I am using Pubsub as a queuing mechanism tool and want to know the count of the messages residing inside the topic of Pubsub. For the same purpose, I have decided to use the Google API metric pubsub.googleapis.com/subscription/num_undelivered_messages but I am unable to figure out how can this be achieved using python client library monitoring_v3.
from google.cloud import monitoring_v3
import time,os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/key.json"
client = monitoring_v3.MetricServiceClient()
project = 'project_name'
project_name = client.project_path(project)
metric_type = "pubsub.googleapis.com/subscription/num_undelivered_messages"
Can you please guide me on how to proceed further and query this google api metric named as num_undelivered_messages?
This works for me but I am not sure if it's the creator's intention.
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "..."
client = monitoring_v3.MetricServiceClient()
result = query.Query(
client,
project,
'pubsub.googleapis.com/subscription/num_undelivered_messages',
minutes=1).as_dataframe()
You might need to run your code this way for a specific subscription:
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
project = "my-project"
client = monitoring_v3.MetricServiceClient()
result = query.Query(client,project,'pubsub.googleapis.com/subscription/num_undelivered_messages', minutes=60).as_dataframe()
print(result['pubsub_subscription'][project]['subscription_name'][0])

Accesing ASANA data using python requests

First of all, I'm not a Python guru as you can probably tell... So here we go.
I'm trying to use Asana's API to pull data with Python requests (Projects, tasks, etc) and doing the authentication using Oauth 2.0... I've been trying to find a simple python script to have something to begin with but I haven't had any luck and I can't find a decent and simple example!
I already created the app and got my client_secret and client_secret. But I don't really know where or how to start... Could anybody help me please?
import sys, os, requests
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import asana
import json
from six import print_
import requests_oauthlib
from requests_oauthlib import OAuth2Session
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
if 'ASANA_CLIENT_ID' in os.environ:
#Creates a client with previously obtained Oauth credentials#
client = asana.Client.oauth(
#Asana Client ID and Secret, set as a Windows environments to avoid hardcoding variables into the script#
client_id=os.environ['ASANA_CLIENT_ID'],
client_secret=os.environ['ASANA_CLIENT_SECRET'],
# this special redirect URI will prompt the user to copy/paste the code.
# useful for command line scripts and other non-web apps
redirect_uri='urn:ietf:wg:oauth:2.0:oob'
)
print ("authorized=", client.session.authorized)
# get an authorization URL:
(url, state) = client.session.authorization_url()
try:
# in a web app you'd redirect the user to this URL when they take action to
# login with Asana or connect their account to Asana
import webbrowser
webbrowser.open(url)
except Exception as e:
print_("Open the following URL in a browser to authorize:")
print_(url)
print_("Copy and paste the returned code from the browser and press enter:")
code = sys.stdin.readline().strip()
# exchange the code for a bearer token
token = client.session.fetch_token(code=code)
#print_("token=", json.dumps(token))
print_("authorized=", client.session.authorized)
me = client.users.me()
print "Hello " + me['name'] + "\n"
params = {'client_id' : client_id, 'redirect_uri' : redirect_uri, 'response_type' : token,}
print_("*************** Request begings *******************"+"\n")
print_("r = requests.get('https://app.asana.com/api/1.0/users/me)" + "\n")
r = requests.get('https://app.asana.com/api/1.0/users/me', params)
print_(r)
print_(r.json)
print_(r.encoding)
workspace_id = me['workspaces'][0]['id']
print_("My workspace ID is" + "\n")
print_(workspace_id)
print_(client.options)
I'm not sure how to use the requests lib with Asana. Their python doc did not help me. I'm trying to pull the available projects and their code colours so I can later plot them into a web browser (For a high-level view of the different projects and their respective colours - Green, yellow or red)
When I introduce the url (https://app.asana.com/api/1.0/users/me) into a browser, it gives me back a json response with the data, but when I try to do the same with the script, it gives me back a 401 (not authorized) response.
Does anybody know what I'm missing / doing wrong?
Thank you!!!
I believe the issue is that the Requests library is a lower level library. You would need to pass all of the parameters to your requests.
Is there a reason you are not exclusively using the Asana Python client library to make requests? All of the data you are looking to fetch from Asana (projects, tasks, etc.) are accessible using the Asana Python library. You will want to look in the library to find the methods you need. For example, the methods for the tasks resource can be found here. I think this approach will be easier (and less error-prone) than switching between the Asana lib and the Requests lib. The Asana lib is actually built on top of Requests (as seen here).

how can i use sharepoint (via soap?) from python?

I want to use Sharepoint with python (C-Python)
Has anyone tried this before ?
I suspect that since this question was answered the SUDS library has been updated to take care of the required authentication itself. After jumping through various hoops, I found this to do the trick:
from suds import WebFault
from suds.client import *
from suds.transport.https import WindowsHttpAuthenticated
user = r'SERVER\user'
password = "yourpassword"
url = "http://sharepointserver/_vti_bin/SiteData.asmx?WSDL"
ntlm = WindowsHttpAuthenticated(username = user, password = password)
client = Client(url, transport=ntlm)
To get the wsdl :
import sys
# we use suds -> https://fedorahosted.org/suds
from suds import WebFault
from suds.client import *
import urllib2
# my 2 url conf
# url_sharepoint,url_NTLM_authproxy
import myconfig as my
# build url
wsdl = '_vti_bin/SiteData.asmx?WSDL'
url = '/'.join([my.url_sharepoint,wsdl])
# we need a NTLM_auth_Proxy -> http://ntlmaps.sourceforge.net/
# follow instruction and get proxy running
proxy_handler = urllib2.ProxyHandler({'http': my.url_NTLM_authproxy })
opener = urllib2.build_opener(proxy_handler)
client = SoapClient(url, {'opener' : opener})
print client.wsdl
main (mean) problem:
the sharepoint-server uses a NTLM-Auth [ :-( ]
so i had to use the NTLM-Auth-Proxy
To Rob and Enzondio : THANKS for your hints !
SOAP with Python is pretty easy. Here's a tutorial from Dive Into Python.
SharePoint exposes several web services which you can use to query and update data.
I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.
This article should give you enough information to get started.
http://www.developer.com/tech/article.php/3104621

Categories