json decod error when using POST in chalice - json

When I try to use app.current_request.json_body in chalice I get a decode error:
Traceback (most recent call last): File "/var/task/chalice/app.py",
line 659, in _get_view_function_response
response = view_function(**function_args) File "/var/task/app.py", line 34, in post_item
data = app.current_request.json_body File "/var/task/chalice/app.py", line 303, in json_body
self._json_body = json.loads(self.raw_body) File "/var/lang/lib/python3.6/json/init.py", line 354, in loads
return _default_decoder.decode(s) File "/var/lang/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/var/lang/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char
0)
It doesn't matter how simple the data is. Example: {"Company":"ABC"} or {}.
As can be seen in the following code in the API Gateway all I try to do is return the data that has been sent so I don't think this is the problem:
#app.route('/test', methods=['POST'], content_types=['application/json'], cors=cors_config)
def post_item(data):
data = app.current_request.json_body
return data
Does anyone know what I might have done wrong?

You must remove the data from the parameters of the function.
That is used for pass url parameters.
#app.route('/test', methods=['POST'], content_types=['application/json'], cors=cors_config)
def post_item():
data = app.current_request.json_body
return data

Related

Receive API body POST by Python

I have a problem with API POST, can you help me?
import requests
import json
url = 'http://xxx/api/getTotalPrice'
param = dict(itineraryType=1,
departureAirportCode='HAN',
destinationAirportCode='DLI',
departureDate='2020-12-30T14:00',
returnDate='2020-12-30T09:00',
adult=1,
children=1,
infant=1
)
resp = requests.post(url=url, params=param)
u_data = resp.json()
print(u_data)
I want to receive data from API POST. This is body API and this made error.
Here, this is error
C:\Users\Admin\PycharmProjects\untitled\venv\Scripts\python.exe C:/Users/Admin/PycharmProjects/untitled/venv/test.py
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\untitled\venv\test.py", line 17, in <module>
u_data = resp.json()
File "C:\Users\Admin\PycharmProjects\untitled\venv\lib\site-packages\requests\models.py", line 900, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Process finished with exit code 1
I can get data from POST API without body, but with body, I cannot.
Can you help to fix code?
Many thanks!
P/S:
Here value which I want to get
{
"departureFlight": {
"totalPrice": 1896000.0,
"airlineCode": "VN"
},
"returnFlight": {
"totalPrice": 3263800.0,
"airlineCode": "VJ"
}
}
OK, I have an answer.
data = {'itineraryType':1,'departureAirportCode':'HAN','destinationAirportCode':'DLI','departureDate':'2020-12-30T15:00','returnDate':'2020-12-30T09:00','adult':1,'children':1,'infant':1}
headers={'Content-type':'application/json', 'Accept':'application/json'}
resp = requests.post(url=url, json=data, headers=headers)
u_data = resp.json()
print(u_data)
change dict(...) to {...} and set headers.

JSONDecodeError: Expecting value: line 1 column 1 error in AWS Lambda

I am trying to write a aws lambda function which will push the SQS queue output in a s3 bucket.
But the lambda function is failing to push the message , the cloudwatch log is showing
JSONDecodeError: Expecting value: line 1 column 1
i am posting the lambda function which i am using
import json
import boto3
def lambda_handler(event, context):
s3 = boto3.client("s3")
data = json.loads(event["Records"][0]["body"]) --getting error in this line
print(data)
s3.put_object(Bucket="sqsmybucket",key="data.json", Body=json.dumps(data))
#print(event)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
The cloud watch log is showing
2020-05-30T23:51:45.276+05:30
[ERROR] JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 6, in lambda_handler
data = json.loads(event["Records"][0]["body"])
File "/var/lang/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/var/lang/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/var/lang/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
I have formatted the message and saved it to the cloud below is the link
[formatted JSON code][1]
formatted JSON
Please help , thanks in advance
Your event["Records"][0]["body"] is a plain string, not json:
"body": "A difficult message."
Therefore, json.loads(event["Records"][0]["body"]) is equivalent to json.loads("A difficult message.") which obviously fails.
To get body's value you can do the following instead:
data = event["Records"][0]["body"]
However, since later you have the following statment:
Body=json.dumps(data)
The Body will be:
Body='"A difficult message."'
which may or may not be what you desire.

Error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I want to create a temporary JSON file to store the google calendar credentials, that were stored in a "job" object.
I am using the ServiceAccountCredentials to then get the credentials from the file.
Client = {
"clientID": job.getClientID(),
"clientSecret": job.getClientSecret()
}
temp = tempfile.NamedTemporaryFile(mode="w+b", suffix=".json")
complex_data = open(temp.name, "w", encoding="UTF-8")
complex_data.write(json.dumps(Client))
# data = complex_data.write(json.dumps(Client))
# z = json.loads(data)
credentials = ServiceAccountCredentials.from_json(
temp.name
)
```
I get the following error:
Traceback (most recent call last):
File "/var/www/library-offers-google-calendar/main.py", line 209, in <module>
temp.name
File "/var/www/library-offers-google-calendar/venv/lib/python3.7/site-packages/oauth2client/service_account.py", line 436, in from_json
json_data = json.loads(_helpers._from_bytes(json_data))
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
From the docs, the method ServiceAccountCredentials.from_json accepts a json data rather than a json file name.
If you want to use a json file name, you need to use the method ServiceAccountCredentials.from_json_keyfile_name
Or else, you can directly use Client dictionary as a parameter to ServiceAccountCredentials.from_json without creating and reading from temporary file.

App randomly crashes with a JSON error

I've posted first the error message with full traceback and the code as well.
The code that is below is within a loop, that will run multiple times changing the variables within the session.get() link for the API data call.
From time to time I will get an error that the json.decoder.JSONDecodeError is expecting value... (full error below)
I can't figure out why.
Traceback (most recent call last):
File "C:\Users\CarlosMiguel\Desktop\experiments\data_collector\data_collector.py", line 100, in <module>
get_data = session.get(api_data_link+symbol+"?limit=1000&period="+i).json()
File "C:\Users\CarlosMiguel\Anaconda3\lib\site-packages\requests\models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Users\CarlosMiguel\Anaconda3\lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\Users\CarlosMiguel\Anaconda3\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\CarlosMiguel\Anaconda3\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Currently It's written like this (everything that needs to be is imported):
try:
get_data = session.get(api_data_link+symbol+"?limit=1000&period="+i).json()
for candle in get_data:
#Do things with the requested data....
except:
print("JSONError")
print('Could not update data for')
print(symbol + ' ' + i)
Could it be that the API just doesn't return anything on some random call?
Because it seems to be completely random when it crashes with that error.
If it could be the API just not returning anything, how could I write it to call it again for a few times, before continuing on with the rest of the app?

Error when using ipapi python API for getting geo location from IP

I am using ipapi to get geo location from IP. It works for most part but get the following error for some of the ip's I tried.
File " ...ipapi\ipapi.py", line 47, in location
return response.json()
ValueError: Expecting value: line 1 column 1 (char 0)
*** print_exc:
File "...\models.py", line 892, in json
return complexjson.loads(self.text, **kwargs)
File "C:\Python34\lib\json\__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "C:\Python34\lib\json\decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python34\lib\json\decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
CODE:
(ip.location(ip=ip_address))
Any suggestions how to resolve this issue??
Thanks