twython get api error code - python

I am trying to get the exception code from Twitter API (using twython), but it returns an HTTP error code instead.
Here you can see the codes from twitter API.
For example:
try:
twitter.retweet(id=tweet["id"])
except TwythonError as e:
print("FAILED to retweet: [tweet_id:" + str(tweet["id"]) + "]")
print(e.error_code)
The following prints HTTP error code instead of twitter API code
print(e.error_code)
For example instead of API error code 261 or 271, 272,... it prints HTTP error 403 (Forbidden).
This is a problem because I cannot distinguish between codes that share the same HTTP error code.

If you print out all of e with print(e), you will get additional information.

Related

How to remove error 500 while using api to get data

Below is the code where I am using yake api to extract keywords, in this I am passing the url in the api and using to get the json objectg but getting error 500 pleasee check, below is the snippet of the code
try:
response = requests.get(f'http://yake.inesctec.pt/yake/v2/extract_keywords?content={url}&max_ngram_size=3&number_of_keywords=20&highlight=true',
params = {"format":"json"})
# print(response)
print(response.json())
except ConnectionError as err: #i am getting error in this line
time.sleep(1)

Google Bigquery streaming (python 3): BadRequest 400 POST No rows present in the request

I stream my data from AppEngine into Bigquery with this code:
errors = client.insert_rows(table, bigquery_rows_to_insert) # API request()
try:
assert errors == []
except AssertionError:
handle_error()
But I'm getting a server error BadRequest 400 POST No rows present in the request.
Why this error could happen? Why didnt exception catch it?

unable to output status_code inside flask restapi

I am using python 3.8, Flask 1.1.2
While trying to handle errors can't figure out a way to return status code and break code when error is found.
When everything runs fine, program return statement is as follows
return jsonify({'status':'success', 'prediction':pred}), 200
which allow me to access status_code
response = requests.post(url_path, json=data)
print(response.status_code)
>>> 200
However when error arise before reaching end of code I've tried to handle error like this:
code....
try:
code
except KeyError:
return jsonify({'error_message':'something wrong with input'}), 10
code...
return jsonify({"status":"success!", "best_actions":final_actions}), 200
When except statement is executed it outputs ConnectionError: ('Connection aborted.', BadStatusLine('HTTP/1.0 10 UNKNOWN\r\n')) which seems to happen when python client receives empty response according to Connection aborted.', BadStatusLine("''",) on server?
changing except statement like:
expect KeyError:
return jsonify({'error_message':'something wrong with input'})
allow me to obtain response.json() however cannot get response.status_code.
returning with http status_code works:
expect KeyError:
return jsonify({'error_message':'something wrong with input'}), 1xx
above code works fine however I am trying to create custom status_codes therefore I can add detailed reason and solution in my documentation.
Any help or guide to helpful resource would be greatly appreciated, thanks!

Capturing Response Body for a HTTP Error in python

Need to capture the response body for a HTTP error in python. Currently using the python request module's raise_for_status(). This method only returns the Status Code and description. Need a way to capture the response body for a detailed error log.
Please suggest alternatives to python requests module if similar required feature is present in some different module. If not then please suggest what changes can be done to existing code to capture the said response body.
Current implementation contains just the following:
resp.raise_for_status()
I guess I'll write this up quickly. This is working fine for me:
try:
r = requests.get('https://www.google.com/404')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err.request.url)
print(err)
print(err.response.text)
you can do something like below, which returns the content of the response, in unicode.
response.text
or
try:
r = requests.get('http://www.google.com/nothere')
r.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
sys.exit(1)
# 404 Client Error: Not Found for url: http://www.google.com/nothere
here you'll get the full explanation on how to handle the exception. please check out Correct way to try/except using Python requests module?
You can log resp.text if resp.status_code >= 400.
There are some tools you may pick up such as Fiddler, Charles, wireshark.
However, those tools can just display the body of the response without including the reason or error stack why the error raises.

Returning response REST API error messages with python

I'm sending a simple REST API call in python:
import json
import requests
import time
url = 'https://server:9899/123456789/open.scan'
data = {'alpha':'one','beta':'two'}
print 'Sending open.scan command: ' + str(data)
try:
response = requests.post(url, data=data, verify=false)
print response.status_code
except:
print "failed"
This all works correctly and triggers the API. However, if the apikey I feed is bad I get back a 405 error (as expected?).
The issue I'm having is this:
When I issue this API call over a web browser as simply:
https://server:9899/api/wrongapikeyhere/open.sesame
The page returned to me actually states "Wrong API key used"
I'm trying to figure out how to get that returned string into my python code so that I can actually print out what the specific error is and not simply a 405.

Categories