Error when extracting data from JSON webhook - python

I am not able to access the data from the event in the python function
I am trying to get the name from the JSON
def handler(event, context):
resp = event
user_name = resp['body']['user']['name']
but I get the following error
ERROR] TypeError: string indices must be integers
Traceback (most recent call last):
File "/var/task/index.py", line 28, in handler
user_name = resp['body']['user']['name']

It seems that resp is of string type. load your response in JSON before accessing it.
import json
resp = json.loads(resp)

The below solution worked for me. The event body should be retrieved first
import json
def handler(event, context):
resp = json.loads(event["body"])
user_name = event['user']['name']

Related

What package and function to use to get a response that can be formatted in JSON after sending a query string

I am currently using AWS Lambda which does not support the "requests" package. Hence I am trying to look for alternatives using urllib3
My code using the "requests" package is as such:
site_dict = {
'1':'JSDOKAJDISADK',
'2':'IOASJD8917238ASDW',
'3':'UIO2NKDNAK123'
for sId in site_dict:
params = {
'api_key': site_dict[sId]
}
r = requests.get(url = id_url, params = params)
data = r.json()
Params is a dictionary where the
Using urllib3:
http = urllib3.PoolManager()
r = http.request('GET', url=id_url, headers=params)
data = r.json()
However, I get the error:
Traceback (most recent call last):
File "C:\Users\Owner\PycharmProjects\pythonProject\API Test.py", line 37, in <module>
data = r.json()
AttributeError: 'HTTPResponse' object has no attribute 'json'
How do I get my data which I can then format into JSON format using urllib3?
Use r.data instead of r.json()
...
data = r.data # and not r.json()
If you want to get Json content you have to use python json module
JSON Content
JSON content can be loaded by decoding and deserializing the data attribute of the request:
import json
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'http://httpbin.org/ip')
json.loads(r.data.decode('utf-8'))
{'origin': '127.0.0.1'}
For more info read the official documentation.

Trying to Authenticate to an API using Python and Store Access Token

I'm getting the following error:
Traceback (most recent call last):
File "authenticate-smartling.py", line 20, in
api_response.json()['response']['data']['accessToken']
KeyError: 'data'
import sys
import os
import requests
import json
# Read authentication credentials from environment
user_id = os.environ.get('DEV_USER_IDENTIFIER')
user_secret = os.environ.get('DEV_USER_SECRET')
project_id = os.environ.get('DEV_PROJECT_ID')
# Authenticate
api_url = 'https://api.smartling.com/auth-api/v2/authenticate'
api_parameters = {
'userIdentifier': user_id,
'userSecret': user_secret
}
api_response = requests.post(api_url, json = api_parameters)
# Store access token for use in subsequent API calls
api_response.json()['response']['data']['accessToken']

Parsing a JSON string and store in a variable

Hi Guys I am calling this API to see the live data of a price from Coingecko, I am trying to parse the json file but keep getting a error in my code when i use json.loads. I imported json and still get this error
Here is a snippet of my code
import json
import requests
class LivePrice(object): #Coingecko API
def GetPrice(self, coin):
coinprice = coin
Gecko_endpoint = 'https://api.coingecko.com/api/v3/simple/price?ids='
currency = '&vs_currencies=usd'
url = Gecko_endpoint + coinprice + currency
r = requests.get(url, headers = {'accept': 'application/json'})
y = json.loads(r)
#print(r.json()[coinprice]['usd'])
if I use this print function i get the price but I want to be able to use the variable and pass it to another class to do some calculation
Just trying to make a simple trading bot for fun while using Alpaca API for paper trading
Traceback (most recent call last):
File "AlapacaBot.py", line 76, in <module>
r.GetPrice(Bitcoin)
File "AlapacaBot.py", line 65, in GetPrice
y = json.loads(r)
File "/usr/lib/python3.8/json/__init__.py", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not Response
I am following the example from w3schools but I keep getting an error
https://www.w3schools.com/python/python_json.asp
json.loads only accepts the types listed in your error.
requests get method returns a Response object, not one of those types. The W3Schools link is not a replacement for the Python Requests module documentation, as it only shows strings, not Response objects.
Response objects have a json() function to get the body as a dictionary, which you commented out
r = requests.get(url, headers = {'accept': 'application/json'})
y = r.json()
print(y[coin]['usd'])
Your code is almost correct. You only need to use the requests.json() to retrieve the json information
import json
import requests
class LivePrice: #Coingecko API
def GetPrice(coin):
coinprice = coin
Gecko_endpoint = 'https://api.coingecko.com/api/v3/simple/price?ids='
currency = '&vs_currencies=usd'
url = Gecko_endpoint + coinprice + currency
r = requests.get(url, headers = {'accept': 'application/json'})
y = r.json()
print(y[coinprice]['usd'])
LivePrice.GetPrice("bitcoin")

Getting error making calls with twilio python api

Getting this error when I try to make a call with the twilio python api:
Jacob-Mac-mini:downloads kovyjacob$ python3 twilio_call.py
Traceback (most recent call last):
File "/Users/kovyjacob/Downloads/twilio_call.py", line 11, in <module>
call = client.calls.create(
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/rest/api/v2010/account/call/__init__.py", line 141, in create
payload = self._version.create(method='POST', uri=self._uri, data=data, )
File "/Users/kovyjacob/Library/Python/3.9/lib/python/site-packages/twilio/base/version.py", line 205, in create
raise self.exception(method, uri, response, 'Unable to create record')
twilio.base.exceptions.TwilioRestException:
HTTP Error Your request was:
POST /Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json
Twilio returned the following information:
Unable to create record: The requested resource /2010-04-01/Accounts/['AC766eaf7ef8d79de658756223cee446df']/Calls.json was not found
More information may be available here:
https://www.twilio.com/docs/errors/20404
I checked the link, but a) I'm not sure what the problem is exactly, and b) it doesn't say how to fix it.
This is the code:
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid = ['AC766eaf7ef8d79de658756223cee446df']
auth_token = ['74ef4743a7a9a748cxxxxxxxxxxxxxxx']
client = Client(account_sid, auth_token)
call = client.calls.create(
twiml='<Response><Say>Ahoy, World!</Say></Response>',
to='+14372341004',
from_='+14243560675'
)
print(call.sid)
account_sid and auth_token should be passed as strings, not array with string inside.
Twillio Rest Client Source Code
Edit your code to:
account_sid = 'AC766eaf7ef8d79de658756223cee446df'
auth_token = '74ef4743a7a9a748cxxxxxxxxxxxxxxx'

'body': KeyError in AWS Lambda function for Telegram Bot

I followed a guide to set up a Telegram Bot through AWS, so after preparing the function (and the gateway API) to handle a simple bot which answers with the same message i stumbled upon a KeyError on the word 'body'. Here's the code:
import json
from botocore.vendored import requests
TELE_TOKEN='700794743:AAFtypDtqP3-dOMC5dSX7DqtwVRGNuKZhH8'
URL = "https://api.telegram.org/bot{}".format(TELE_TOKEN)
def send_message(text, chat_id):
final_text = "You said: " + text
url = URL + "/sendMessage?text={}&chat_id={}".format(final_text, chat_id)
requests.get(url)
def lambda_handler(event, context):
message = json.loads(event['body'])
chat_id = message['message']['chat']['id']
reply = message['message']['text']
send_message(reply, chat_id)
return {
'statusCode': 200
}
'body': KeyError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 13, in lambda_handler
message = json.loads(event['body'])
KeyError: 'body'
I don't know what could possibly be wrong, maybe the 'event' json file doesn't actually have a 'body' parameter? Any help with this would be appreciated!

Categories

Resources