I am trying to POST request from my flutter application to the Flask REST API, testing API with POST MAN has no problem, but on flutter I am getting error in flutter like this:
I/flutter ( 6378): FormatException: Unexpected character (at character 1)
I/flutter ( 6378):
I/flutter ( 6378): ^
and in Flask APP like this:
[2020-01-23 11:42:32,517] ERROR in app: Exception on /cards [POST]
Traceback (most recent call last):
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/_compat.py", line 36, in reraise
raise value
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/home/shaukat/.local/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functionsrule.endpoint
File "/home/shaukat/Projects/udemy flask rest API and python/rest-api-sections-master/section3/app.py", line 19, in create_card
'id': request_data["id"],
TypeError: 'NoneType' object is not subscriptable
127.0.0.1 - - [23/Jan/2020 11:42:32] "POST /cards HTTP/1.1" 500 -
My code in flutter:
Future<void> addNewCard(NewCard product) async {
const url = 'http://10.0.2.2:5000/cards';
try {
final response = await http.post(
url,
body: json.encode({
'id': product.id,
'cardNo': product.cardNo,
'cardType': product.cardType,
'amount': product.amount,
}),
);
final newProduct = NewCard(
id: json.decode(response.body)['id'],
cardNo: product.cardNo,
cardType: product.cardType,
amount: product.amount,
);
print(newProduct);
_newCard.add(product);
// _items.insert(0, newProduct); // at the start of the list
notifyListeners();
} catch (error) {
print(error);
throw error;
}}
code in python Flask:
#app.route('/cards', methods=['POST'])
def create_card():
request_data = request.get_json()
new_cards = {
'id': request_data["id"],
'cardNo': request_data["cardNo"],
'cardType': request_data["cardType"],
'amount': request_data["amount"],
}
cards.append(new_cards)
return jsonify(cards)
I eventually found the solution in a comment of this post Flutter POST request body not sent
I had to add headers: {"Content-Type": "application/json"}
in my post request. thanks for your help
line 19, in create_card 'id': request_data["id"], TypeError: 'NoneType' object is not subscriptable
As you see the server is unable to get the data / parse it.
I'd suggest to debug it inside the REST server and check if you are even receving the values..
I understand that postman works for you, but once you understand what are you even getting # the server it will be easier to fix what flutter sends.
my guess is that product.id (flutter code) is an int and not a string..
please send a more detailed debug information to help resolve this.
good luck.
Related
Hi I'm trying amadeus api flight offer search api but getting 400 error, cross checked my client and secret ID and its correct not sure is there any issue with api or what.
code:
from amadeus import Client, ResponseError, Location
import json
AMADEUS = Client(
client_id='my client id',
client_secret='my secret'
)
try:
response = AMADEUS.shopping.flight_offers_search.get(
originLocationCode='MAD',
destinationLocationCode='ATH',
departureDate='2022-07-26')
resp = json.dumps(response.data, indent=4)
resp = json.loads(resp)
# print(resp)
print(resp)
except ResponseError as error:
print(error)
Exception:
File "C:\Users\ASUS\python_workspace\python_practiceCode\test_file.py", line 261, in <module>
response = AMADEUS.shopping.flight_offers_search.get(
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\shopping\_flight_offers_search.py", line 32, in get
return self.client.get('/v2/shopping/flight-offers', **params)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\http.py", line 40, in get
return self.request('GET', path, params)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\http.py", line 110, in request
return self._unauthenticated_request(
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\http.py", line 126, in _unauthenticated_request
return self.__execute(request)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\http.py", line 152, in __execute
response._detect_error(self)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\parser.py", line 16, in _detect_error
self.__raise_error(error, client)
File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\amadeus\mixins\parser.py", line 67, in __raise_error
raise error
amadeus.client.errors.ClientError: [400]
In your API call, you are missing the mandatory parameter adults. Please check out the API reference for more details.
I am trying to connect to a BigQuery table from a google cloud function but my function returns the following error:
Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging Details:
500 Internal Server Error: The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
When I inspect the logs, I see the following error:
Traceback (most recent call last): File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 2073, in wsgi_app response = self.full_dispatch_request() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1518, in full_dispatch_request rv = self.handle_user_exception(e) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1516, in full_dispatch_request rv = self.dispatch_request() File "/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py", line 1502, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "/layers/google.python.pip/pip/lib/python3.9/site-packages/functions_framework/init.py", line 99, in view_func return function(request._get_current_object()) File "/workspace/main.py", line 72, in entry client = bigquery.Client() AttributeError: 'function' object has no attribute 'Client'
I don't understand why the attribute 'Client' doesn't exist. I believe I have imported bigquery correctly. Here is my entry point function with the simple test script:
import os
import json
from google.cloud import bigquery
def entry(request):
client = bigquery.Client()
query_job = client.query("""SELECT MAX(day) FROM `name of project and bigquery table`""")
for i in query_job:
print(i[0])
return "ok"
Here is my requirements.txt file
google-cloud-bigquery
sqlalchemy==1.4.37
pandas==1.4.2
PyMySQL==1.0.2
Any pointers would be greatly appreciated.
UPDATE
I had another function within my cloud function with was called bigquery. I think this caused a conflict with my import of bigquery in the third line of my code. I believe this is the root cause of my issue.
Getting HTTP 400 bad request from testrail server when i try to post testcase result using urllib in python3. Appreciate if someone help me on this. Thanks!
Below is code,
import urllib.request
import json
import base64
data = {'results':[{'case_id': '123','status_id': '1','comment': 'This test passed', 'version': '0.14.0-W9'}]}
headers = {}
post_data = urllib.parse.urlencode(data).encode()
auth = base64.b64encode(b'user:pass')
auth = auth.decode()
headers['Authorization'] = 'Basic %s' % auth
headers['Content-Type'] = 'application/json'
request = urllib.request.Request("http://testrail.com/index.php?/api/v2/add_results_for_cases/272374", data = post_data, headers = headers)
response = urllib.request.urlopen(request).read()
result = json.loads(response)
print(result)
And error output,
Traceback (most recent call last):
File "p3.py", line 13, in <module>
response = urllib.request.urlopen(request).read()
File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.6/urllib/request.py", line 532, in open
response = meth(req, response)
File "/usr/lib/python3.6/urllib/request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.6/urllib/request.py", line 570, in error
return self._call_chain(*args)
File "/usr/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/lib/python3.6/urllib/request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: Bad Request
Thanks Tomalak and Amiy for quick suggestions.
I have tried testrailAPI library of python3 and it works as expected.
I have a script(test.py) to test some api, like this:
def get_response(fct, data, method=GET):
"""
Performs the query to the server and returns a string containing the
response.
"""
assert(method in (GET, POST))
url = f'http://{hostname}:{port}/{fct}'
if method == GET:
encode_data = parse.urlencode(data)
response = request.urlopen(f'{url}?{encode_data}')
elif method == POST:
response = request.urlopen(url, parse.urlencode(data).encode('ascii'))
return response.read()
In terminal I call:
python test.py -H 0.0.0.0 -P 5000 --add-data
The traceback:
Traceback (most recent call last):
File "test.py", line 256, in <module>
add_plays()
File "test.py", line 82, in add_plays
get_response("add_channel", {"name": channel}, method=POST)
File "test.py", line 43, in get_response
response = request.urlopen(url, parse.urlencode(data).encode('ascii'))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 223, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 532, in open
response = meth(req, response)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 642, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 570, in error
return self._call_chain(*args)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 504, in _call_chain
result = func(*args)
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py", line 650, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: BAD REQUEST
The data is {"name": "Channel1"}. I couldn't understand what is wrong. Please can someone give some tip or show whats's wrong?
When I call using curl, works:
curl -X POST -H "Content-Type: application/json" -d '{"name": "Channel1"}' http://0.0.0.0:5000/add_channel
I solved the problem change the test script:
The api was expected a JSON_MIME_TYPE = 'application/json', so I add a header in a request as follow bellow.
The scrit was using a wrong encode because some text in JSON couldn't be encode in Unicode, Eg:"Omö" encode in ascii launch the exception UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 1: ordinal not in range(128). So I changed to utf8.
Here is the fixed code:
def get_response(fct, data, method=GET):
"""
Performs the query to the server and returns a string containing the
response.
"""
assert(method in (GET, POST))
url = f'http://{hostname}:{port}/{fct}'
if method == GET:
encode_data = parse.urlencode(data)
req = request.Request(f'{url}?{encode_data}'
, headers={'content-type': 'application/json'})
response = request.urlopen(req)
elif method == POST:
params = json.dumps(data)
binary_data = params.encode('utf8')
req = request.Request(url
, data= binary_data
, headers={'content-type': 'application/json'})
response = request.urlopen(req)
x = response.read()
return x
Trying to use Python Twitter Tools to search for the tweeets containing a hashtag. (On a raspberry Pi with python3).
from twitter import *
token = "token"
token_key = "token_key"
con_secret = "con_secret"
con_secret_key = "con_secret_key"
t = Twitter(
auth=OAuth(token, token_key, con_secret, con_secret_key))
print(t.search.tweets(q="#test"))
But I always get a Authorization error.
Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 319, in _handle_response
handle = urllib_request.urlopen(req, **kwargs)
File "/usr/lib/python3.4/urllib/request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "/usr/lib/python3.4/urllib/request.py", line 461, in open
response = meth(req, response)
File "/usr/lib/python3.4/urllib/request.py", line 571, in http_response
'http', request, response, code, msg, hdrs)
File "/usr/lib/python3.4/urllib/request.py", line 499, in error
return self._call_chain(*args)
File "/usr/lib/python3.4/urllib/request.py", line 433, in _call_chain
result = func(*args)
File "/usr/lib/python3.4/urllib/request.py", line 579, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 401: Authorization Required
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "twitter-test.py", line 10, in <module>
print(t.search.tweets(q="#test"))
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 312, in __call__
return self._handle_response(req, uri, arg_data, _timeout)
File "/usr/local/lib/python3.4/dist-packages/twitter/api.py", line 345, in _handle_response
raise TwitterHTTPError(e, uri, self.format, arg_data)
twitter.api.TwitterHTTPError: Twitter sent status 401 for URL: 1.1/search/tweets.json using parameters: (oauth_consumer_key=**key**&oauth_nonce=**nonce**&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1438333973&oauth_token=**token**&oauth_version=1.0&q=%23test&oauth_signature=**signature**)
details: {'errors': [{'code': 32, 'message': 'Could not authenticate you.'}]}
I have tried checking my time (and changing the timezone).
I have tried putting in a callback URL into the app settings and regenerating the keys.
Any help appreciated
Thanks
Couldn't fix this so moved to tweepy library which works a treat!