Docusign Python SDK Authentication Example Error: Bad Request - python

I am trying to use the Docusign Rest API and attempted to follow the sample code on the Python SDK on Github here: https://github.com/docusign/docusign-python-client. I've replaced the necessary values with those obtained from Docusign (keys, urls etc) but the example seems to break down at the following line:
api_client.configure_jwt_authorization_flow(private_key_filename, oauth_base_url, integrator_key, user_id, 3600)
Before then, the code takes the given information and creates the url to authenticate as I understand it. I've manually accessed this link and it seems to work; it asks me for permission to allow the program to act on my behalf and then redirects me to the redirect uri with a code added to the uri. My problem is that when it executes the next line (the one I posted above), it results in this:
Traceback (most recent call last):
File "<ipython-input-40-84847e506c37>", line 1, in <module>
runfile('C:/Users/santi/Desktop/docusign/untitled0.py', wdir='C:/Users/santi/Desktop/docusign')
File "C:\Users\santi\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\santi\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/santi/Desktop/docusign/untitled0.py", line 501, in <module>
api_client.configure_jwt_authorization_flow(private_key_filename, oauth_base_url, integrator_key, user_id, 3600)
File "C:\Users\santi\Anaconda3\lib\site-packages\docusign_esign\api_client.py", line 126, in configure_jwt_authorization_flow
post_params=self.sanitize_for_serialization({"assertion": assertion, "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer"}))
File "C:\Users\santi\Anaconda3\lib\site-packages\docusign_esign\api_client.py", line 430, in request
body=body)
File "C:\Users\santi\Anaconda3\lib\site-packages\docusign_esign\rest.py", line 244, in POST
body=body)
File "C:\Users\santi\Anaconda3\lib\site-packages\docusign_esign\rest.py", line 200, in request
raise ApiException(http_resp=r)
ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'private', 'Content-Type': 'text/html', 'X-AspNetMvc-Version': '5.2', 'X-DocuSign-TraceToken': '15fb83c2-9054-4522-b5ed-b77646fe1c4b', 'X-DocuSign-Node': 'DA2DFE4', 'Date': 'Sun, 05 Aug 2018 19:35:12 GMT', 'Content-Length': '11'})
HTTP response body: b'Bad Request'
I've googled the problem and found some similar errors on here but none that helped me out much. Following the traceback takes me into the api_client.py and rest.py files but I wasn't able to decipher much. In the end the origin in the error seems to be in line 200 of rest.py where an exception is raised because a value unknown to me is not within the proper range. I'm not sure what is causing the bad request on my end. Has anyone had a similar experience or might know what the issue is? I'd appreciate it a lot, thanks.

I was getting exactly the same error at the same line.
The account specific inputs to api_client.configure_jwt_authorization_flow() are:
the private_key_filename (which is processed correctly to get a JWT token)
the oauth_base_url (which is hard coded in the example as
"account-d.docusign.com")
the integrator_key (copy-pasted from my account)
the user_id
It turns out that the user_id value should the API Username code. That fixed the problem. I found the answer here:
DocuSign Python SDK - API Exception 400 - 'Bad Request'
Hope it solves your problem too!

Related

How to fix "The request specifies an invalid page token" error with youtube api?

#given the playlist id this will return a list of the
#of all videos in the playlist
#
def get_videos_in_playlist(self,playlist_id):
list_of_videos=list()
next_page=None
##python does not have a do while loop this is very similar to one
while True:
request=self.api_resource.playlistItems().list(
part="id,snippet,contentDetails,status",
playlistId=playlist_id,
maxResults=50,
pageToken=next_page
)
response=request.execute()
next_page=response["nextPageToken"]
for video in response["items"]:
list_of_videos.append(video["contentDetails"]["videoId"])
if next_page==None:
return list_of_videos
I am trying to write a method in python using the youtube api that will take the ID of a playlist and return the ID's of all videos in the playlist. I expect it to run through each page of 50 videos before returning the list. However, it ends up throwing this error:
Traceback (most recent call last):
File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 86, in <module>
youtube_info.test()
File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 20, in test
first_video_id=object.get_videos_in_playlist(id_of_playlist)[0]
File "C:\Users\vdh24\source\repos\GraphAnalysis\youtube_info.py", line 50, in get_videos_in_playlist
response=request.execute()
File "C:\Users\vdh24\AppData\Roaming\Python\Python37\site-packages\googleapiclient\_helpers.py", line 131, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:\Users\vdh24\AppData\Roaming\Python\Python37\site-packages\googleapiclient\http.py", line 937, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=id%2Csnippet%2CcontentDetails%2Cstatus&playlistId=UUL5YbN5WLFD8dLIegT5QAbA&maxResults=50&pageToken=CN4CEAA&key=AIzaSyD1iei5Po9z1Qu7eSGZdzr357LMpLWnr4U&alt=json returned "The request specifies an invalid page token.". Details: "[{'message': 'The request specifies an invalid page token.', 'domain': 'youtube.parameter', 'reason': 'invalidPageToken', 'location': 'pageToken', 'locationType': 'parameter'}]">
The thread 'MainThread' (0x1) has exited with code 0 (0x0)
I tried using the advice from this:
How do I list more than 50 Youtube videos in a channel using nextPageToken?
But it seemed to be what I was already doing. This error was particularly confusing because it seemed to occur at a different page each time I ran the code. Thanks in advance.

HttpEroor 500 Backend Error and HttpError 403 using DoubleClick Bid Manager API in python

I need to create and run some queries as well as get the last reports via DoubleClick Bid Manager API in python, after following the example get_last_report.py in Github step by step, I always got an HttpError 500, like:
Traceback (most recent call last):
File "dbm.py", line 202, in <module>
main(util.setup(args), args.output_directory, QUERY_ID, args.report_window)
File "dbm.py", line 154, in main
response = doubleclick_bid_manager.queries().listqueries().execute()
File "//anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "//anaconda3/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 500 when requesting https://www.googleapis.com/doubleclickbidmanager/v1.1/queries?alt=json returned "Backend Error">
Also when I tried to run the example download_line_items.py, I got another error HttpError 403:
Traceback (most recent call last):
File "download_LI.py", line 81, in <module>
main(util.setup(args), path, request_body)
File "download_LI.py", line 57, in main
handler.write(request.execute()['lineItems'].encode('utf-8'))
File "//anaconda3/lib/python3.7/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "//anaconda3/lib/python3.7/site-packages/googleapiclient/http.py", line 856, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/doubleclickbidmanager/v1.1/lineitems/downloadlineitems?alt=json returned "You are not authorized to use DoubleClick Bid Manager API. Please contact dbm-support#google.com.">
I already tried different client secret files, but it didn't work. Any help will be appreciated.
Problem resovled, the account we connecte need access to DBM. Just need to add the google connection account to DBM for all service operation.
This error is very vague, but it always has to be with a tiny error in the request body.
For those in the future:
Check carefully how to create the query body:
https://developers.google.com/bid-manager/v1.1/queries#resource
More than one time I lost miserable hours debugging... and in the end it was:
a typo in a key name
an extra space like: .... "frequency": "ONE_TIME "
Hope it helps :)

Google Cloud Storage - PUT Fails on Development Server

On my dev server, Google Cloud Storage fails to save files during a PUT command.
This same command works fine on production. The response headers (see below) have little debug information. I have plenty of space on my hard-drive, and I have been running the dev server as an administrator, so it should have all necessary permissions.
Any ideas?
Below is the relevant Traceback (I changed the bucket name):
INFO 2015-08-07 14:14:41,415 module.py:809] default: "PUT /_ah/gcs/bucket/IPR2013-00219%2C%20No.%2016%20Institution%20Decision%20-%20Decis_2015-08-07%2018-14-25.100000.pdf?upload_id=encoded_gs_file%3AZG9ja2V0YWxhcm0tZGV2L0lQUjIwMTMtMDAyMTksIE5vLiAxNiBJbnN0aXR1dGlvbiBEZWNpc2lvbiAtIERlY2lzXzIwMTUtMDgtMDcgMTgtMTQtMjUuMTAwMDAwLnBkZg%3D%3D HTTP/1.1" 500 -
Traceback (most recent call last):
File "Project\libs\cloudstorage\storage_api.py", line 794, in __exit__
self.close()
File "Project\libs\cloudstorage\storage_api.py", line 787, in close
self._flush(finish=True)
File "Project\libs\cloudstorage\storage_api.py", line 841, in _flush
self._send_data(data, self._written, file_len)
File "Project\libs\cloudstorage\storage_api.py", line 874, in _send_data
{'upload_path': self._path_with_token})
File "Project\libs\cloudstorage\errors.py", line 141, in check_status
raise ServerError(msg)
ServerError: Expect status [200] from Google Storage. But got status 500.
Path: '/bucket/IPR2013-00219%2C%20No.%2016%20Institution%20Decision%20-%20Decis_2015-08-07%2018-14-25.100000.pdf'.
Request headers: {'accept-encoding': 'gzip, *', 'content-range': 'bytes 0-195060/195061', 'x-goog-api-version': '2'}.
Response headers: {'date': 'Fri, 07 Aug 2015 18:14:41 GMT', 'transfer-encoding': 'chunked', 'server': 'Development/2.0'}.
Body: ''.
Extra info: {'upload_path': '/bucket/IPR2013-00219%2C%20No.%2016%20Institution%20Decision%20-%20Decis_2015-08-07%2018-14-25.100000.pdf?upload_id=encoded_gs_file%3AZG9ja2V0YWxhcm0tZGV2L0lQUjIw
MTMtMDAyMTksIE5vLiAxNiBJbnN0aXR1dGlvbiBEZWNpc2lvbiAtIERlY2lzXzIwMTUtMDgtMDcgMTgtMTQtMjUuMTAwMDAwLnBkZg%3D%3D'}.
Update 2020
FYI, I raised this issue with Google here, and they said that they won't fix it because it has already been fixed, even though it clearly has not.
Update 2022
Still broken! See the proposed patch in the issue with Google.

Error 429 when invoking Reddit api from Google App Engine

I have been running a cron job on Google App Engine for over a month now without any issues. The job does a variety of things, one being that it uses urllib2 to make a call to retrieve a json response from Reddit as well as a few other sites. About two weeks ago I started seeing errors when invoking Reddit, but no errors when invoking the other sites. The error I am receiving is HTTP error 429.
I have tried executing the same code outside of Google App Engine and do not have any issues. I tried using urlFetch, but receive the same error.
You can see the error when using the app engine's interactive shell with the following code.
import urllib2
data = urllib2.urlopen('http://www.reddit.com/r/Music/.json', timeout=60)
Edit: Not sure why it always fails for me and not someone else. This is the error that I receive:
>>> import urllib2
>>> data = urllib2.urlopen('http://www.reddit.com/r/Music/.json', timeout=60)
Traceback (most recent call last):
File "/base/data/home/apps/s~shell-27/1.356011914885973647/shell.py", line 267, in get
exec compiled in statement_module.__dict__
File "<string>", line 1, in <module>
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/base/python27_runtime/python27_dist/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 429: Unknown
similar code running outside of app engine with no problem:
print urllib2.urlopen('http://www.reddit.com/r/Music/.json').read()
At first I thought it had to do with a timeout problem since it was originally working, but since there is not a timeout error but a the strange HttpError code, I'm not sure.
Any ideas?
Reddit rate limits the api pretty severely for the default user agent for the python shell. You need to set a unique user agent with your reddit username in it, like this:
User-Agent: super happy flair bot by /u/spladug
More info about the reddit api here https://github.com/reddit/reddit/wiki/API.
It's possible that Reddit is counting calls based on IP - which means that other applications on GAE which share your IP might already be exhausting the quota.
This might get better if you use Reddit API keys (I don't know if they issue them) or if they agree to rate limit API calls based on the app header.

How do I get the Google AdWords API Python Client Library to work?

Is there an up-to-date tutorial available for using the Python adwords client, or failing that does anyone know enough to unpick the following? Have I made some configuration error, or perhaps is Python 2.6 unsupported?
On Windows I've installed:
Python 2.6
setuptools-0.6c11.win32-py2.6.exe
PyXML-0.8.4
SOAPpy-0.12.4
ZSI-2.0-rc3
adwords_api_python_13.2.0
I've supplied the AdWords config program with the MCC account email address, its password, blank client email and id, and for the developer token the same email address with "+USD" appended.
Now, if I use SOAPpy as the SOAP library, I get an exception about an unexpected keyword parameter timeout, which has been supplied by one function in SOAPpy to another function in SOAPpy.
If I use ZSI as the SOAP library (which I believe is preferred), I get the following exception:
Traceback (most recent call last):
File "tutorial.py", line 36, in <module>
campaigns = campaign_service.Mutate(operations)[0]
File "c:\Python26\lib\site-packages\adspygoogle\adwords\CampaignService.py", l
ine 112, in Mutate
'Campaign', self._loc, request)
File "c:\Python26\lib\site-packages\adspygoogle\adwords\AdWordsWebService.py",
line 256, in CallMethod
self.__ManageSoap(buf, start_time, stop_time, error)
File "c:\Python26\lib\site-packages\adspygoogle\adwords\AdWordsWebService.py",
line 130, in __ManageSoap
raise Error(e)
adspygoogle.common.Errors.Error:
Traceback (most recent call last):
File "c:\Python26\lib\site-packages\adspygoogle\common\WebService.py", line 20
8, in CallMethod
eval('service.%s(request)' % method_name))
File "<string>", line 1, in <module>
File "c:\Python26\lib\site-packages\adspygoogle\adwords\zsi\v201008\CampaignSe
rvice_services.py", line 47, in mutateCampaign
self.binding.Send(None, None, request, soapaction="", **kw)
File "build\bdist.win32\egg\ZSI\client.py", line 267, in Send
self.SendSOAPData(soapdata, url, soapaction, **kw)
File "build\bdist.win32\egg\ZSI\client.py", line 301, in SendSOAPData
self.h.send(soapdata)
File "c:\Python26\lib\site-packages\adspygoogle\common\zsi\HttpsConnectionHand
ler.py", line 93, in send
httplib.HTTPSConnection.endheaders(self)
File "c:\Python26\lib\httplib.py", line 892, in endheaders
self._send_output()
File "c:\Python26\lib\httplib.py", line 764, in _send_output
self.send(msg)
File "c:\Python26\lib\site-packages\adspygoogle\common\zsi\HttpsConnectionHand
ler.py", line 93, in send
httplib.HTTPSConnection.endheaders(self)
File "c:\Python26\lib\httplib.py", line 890, in endheaders
raise CannotSendHeader()
CannotSendHeader [RAW DATA: _________________________________ Tue Mar 08 16:54:4
0 2011 REQUEST:
followed by some XML, which I've modified to remove identifying data:
<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xm
lns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ZSI="http://www.z
olera.com/schemas/ZSI/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance"><SOAP-ENV:Header><RequestHeader xmlns
="https://adwords.google.com/api/adwords/cm/v201008"><authToken>XYZ</authToken>
<userAgent>AwApi-Python-13.2.0|XYZ</userAgent><developerTok
en>XYZ#gmail.com+USD</developerToken></RequestHeader></SOAP-ENV:Header><SO
AP-ENV:Body xmlns:ns1="https://adwords.google.com/api/adwords/cm/v201008"><ns1:m
utate xmlns:ns1="https://adwords.google.com/api/adwords/cm/v201008"><ns1:operati
ons><ns1:operator>ADD</ns1:operator><ns1:operand><ns1:name>Interplanetary Cruise
#201138165440485000</ns1:name><ns1:status>PAUSED</ns1:status><ns1:endDate>20120
101</ns1:endDate><ns1:budget xsi:type="ns1:Budget"><ns1:period>DAILY</ns1:period
><ns1:amount xsi:type="ns1:Money"><ns1:microAmount>50000000</ns1:microAmount></n
s1:amount><ns1:deliveryMethod>STANDARD</ns1:deliveryMethod></ns1:budget><ns1:bid
dingStrategy xsi:type="ns1:ManualCPC"></ns1:biddingStrategy></ns1:operand></ns1:
operations></ns1:mutate></SOAP-ENV:Body></SOAP-ENV:Envelope>
My code is below:
from adspygoogle.adwords.AdWordsClient import AdWordsClient
from adspygoogle.common import Utils
client = AdWordsClient(path = '../../installers/adwords_api_python_13.2.0.tar/adwords_api_python_13.2.0')
campaign_service = client.GetCampaignService('https://adwords-sandbox.google.com', 'v201008')
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%s' % Utils.GetUniqueName(),
'status': 'PAUSED',
'biddingStrategy': {
'type': 'ManualCPC'
},
'endDate': '20120101',
'budget': {
'period': 'DAILY',
'amount': {
'microAmount': '50000000'
},
'deliveryMethod': 'STANDARD'
}
}
}]
campaigns = campaign_service.Mutate(operations)[0]
# Display results.
for campaign in campaigns['value']:
print ('Campaign with name \'%s\' and id \'%s\' was added.'
% (campaign['name'], campaign['id']))
print
print ('Usage: %s units, %s operations' % (client.GetUnits(),
client.GetOperations()))
Note that the tutorial code at http://code.google.com/apis/adwords/docs/tutorial.html doesn't even slightly work, there's no such thing as aw_api.Client in the current version of the client. But the above is mostly copied from the tutorial.
The examples provided with the client result in the same error.
I could try an older client library if the current one is simply broken, although if it makes any difference, I will need one that supports TargetingIdeaService.
[Edit: oh, sorry, I forgot to say that I actually edited the AdWords client code. In Utils.GetDataFromCsvFile, I removed .replace(':','|') from the line that constructs the file url passed to urllib.urlopen.
This is what makes me suspect that my version of Python might not be supported, since Windows Python 2.6 didn't seem able to open the url file:///c|/foo/bar/baz/]
Have you tried with ZSI-2.0? This issue report looks similar to http://code.google.com/p/google-api-adwords-python-lib/issues/detail?id=141. Please append your info to the bug report, if you continue to see this issue.
As for tutorial code being out of date, good catch! I'll have it fixed shortly. Please track at http://code.google.com/p/google-api-adwords-python-lib/issues/detail?id=152.

Categories

Resources