How do I serialize this JSON response from API in Python? - python

The response from the API is:
{"states":[{"state_id":1,"state_name":"Andaman and Nicobar Islands"},{"state_id":2,"state_name":"Andhra Pradesh"},{"state_id":3,"state_name":"Arunachal Pradesh"},{"state_id":4,"state_name":"Assam"},{"state_id":5,"state_name":"Bihar"},{"state_id":6,"state_name":"Chandigarh"},{"state_id":7,"state_name":"Chhattisgarh"},{"state_id":8,"state_name":"Dadra and Nagar Haveli"},{"state_id":37,"state_name":"Daman and Diu"},{"state_id":9,"state_name":"Delhi"},{"state_id":10,"state_name":"Goa"},{"state_id":11,"state_name":"Gujarat"},{"state_id":12,"state_name":"Haryana"},{"state_id":13,"state_name":"Himachal Pradesh"},{"state_id":14,"state_name":"Jammu and Kashmir"},{"state_id":15,"state_name":"Jharkhand"},{"state_id":16,"state_name":"Karnataka"},{"state_id":17,"state_name":"Kerala"},{"state_id":18,"state_name":"Ladakh"},{"state_id":19,"state_name":"Lakshadweep"},{"state_id":20,"state_name":"Madhya Pradesh"},{"state_id":21,"state_name":"Maharashtra"},{"state_id":22,"state_name":"Manipur"},{"state_id":23,"state_name":"Meghalaya"},{"state_id":24,"state_name":"Mizoram"},{"state_id":25,"state_name":"Nagaland"},{"state_id":26,"state_name":"Odisha"},{"state_id":27,"state_name":"Puducherry"},{"state_id":28,"state_name":"Punjab"},{"state_id":29,"state_name":"Rajasthan"},{"state_id":30,"state_name":"Sikkim"},{"state_id":31,"state_name":"Tamil Nadu"},{"state_id":32,"state_name":"Telangana"},{"state_id":33,"state_name":"Tripura"},{"state_id":34,"state_name":"Uttar Pradesh"},{"state_id":35,"state_name":"Uttarakhand"},{"state_id":36,"state_name":"West Bengal"}],"ttl":24}
I am trying to send this data to my Telegram bot.
states_url = "https://cdn-api.co-vin.in/api/v2/admin/location/states"
res = requests.get(states_url,headers={'User-Agent':my_headers})
bot.send_message(chat_id = chat_id, text=response)
I am getting this error:
TypeError: Object of type Response is not JSON serializable

You're trying to send the Response object, while you want either the Python object from the response, in which case you can use res.json(), or you want the raw text of the response, in which case you can use res.text.

Related

Python requests post api errors

I need add friend on faceit by api. There my code
facapi = 'Bearer xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
targetid = '54372d6d-134f-4a0d-90c1-babccfaf9e08'
headers = {"Authorization":facapi,"users":[targetid]}
payload={"users":targetid,"conversionPoint":"profile"}
url = f'https://api.faceit.com/friend-requests/v1/users/{myfaceitid}/requests'
print(requests.post(url, headers=headers ).text)
When i send post request i get that
requests.exceptions.InvalidHeader: Header part ([targetid]) from {'users': [targetid]} must be of type str or bytes, not <class 'list'>
Im changed [targetid] to targetid and got another error
{"errors":[{"code":"err_br0","message":"'users' field must contain user ids"}]}
The joke is that the first request contains a list of user ids and the request requires a string type or byte, and the second request already contains just a string with userid and the error requires this uid
Also tried to add payload, but in that case i got another error
{"errors":[{"code":"err_br0","message":"invalid character 'u' looking for beginning of value"}]}
<bound method Response.json of <Response [400]>>
My payload is silimar to faceit payload
payload={"users":'7efe7dc4-23cc-43c0-b0ac-25fe3385ef71',"conversionPoint":"matchroom"}
idk how to fix that. It feels broken

Python POST Request x-www-form-urlencoded received error "Object of type Response is not JSON serializable"

i'm having an issue while write codes for consume another API using Python + Flask + Requests.
their API using PHP with x-www-form-urlencoded instead of RAW JSON, here is my code :
app = Flask(__name__)
#app.route('/api/test/getinfo', methods=['POST'])
def get_house_info():
if request.method == 'POST':
try:
payloads = {'no_house':'001234123', 'cd_agent' : '01', 'nm_agent' : 'ABC'}
response_data = requests.post(url=url, headers=headers, data=payloads)
return response_data
except Exception as e:
return(str(e))
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
after that i run this flask and tried to call this endpoint using postman
but i received error Object of type Response is not JSON serializable is there something wrong in my codes ?
Try json.dumps() for payloads
python dictionary and json is not the same, refer to its usage here:
Note: Keys in key/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys. source
From python to json : json.dumps(x)
From json to python : json.loads(x)

Event Hub Converting JSON to JSON String

When we try to publish the json to Azure Event hub, EventData converting the JSON string. Instead of JSON string I need the JSON only at the consumer end.
response = {"status":"Active", "code":400}
event_batch = await producer.create_batch()
event_batch.add(EventData(json.dumps(response)))
At the consumer end I am getting the event as { body: '{"status":"Active", "code":400}', 'sequence_numbe':1} like this. how can we get only Json at consumer end like this
{ body: {"status":"Active", "code":400}, 'sequence_numbe':1}
Can anyone help?
You could use body_as_json method to achieve your requirement.
Sample Implementation :
jsonbody = event.body_as_json(encoding='UTF-8')
This will directly return us the JSON Object
Alternate Approach :
Get it as string and then convert the same to json object.
jsonbody = json.loads(event.body_as_str(encoding='UTF-8')))

API request in python and "Process finished with exit code 0"

I am requesting an api and get the following response and not getting my results.
For IDE I am using pycharm community edition.
import requests
import json
def tes():
url="https://user-service.abc.co.in/api/user/admin/roles/"
header ={'Content-Type': 'application/json' }
payload ={'phone_number': '9999999999'}
resp=requests.get(url,headers=header,data=json.dump(payload,indent=4))
assert resp.status_code==200
resp_body=resp.json()
assert resp_body['url']==url
print(resp.text)
Please help me why this is happening.
In the line resp=requests.get(url,headers=header,data=json.dump(payload,indent=4)) you are trying to convert the payload to json but you called json.dump() which expects a file-like object as second parameter. From the docs:
json.dump(obj, fp)
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object) Python docs for json.dump()
For your purposes you want to use json.dumps(obj) (notice the 's' at the end) which
Serialize obj to a JSON formatted str
Python docs for json.dumps()

python telegram bot issue: accessing json data

im building a script in python for a chat group. i am trying to add a / command for the user to get info from a json output. i can have them see the full json output like
def eosvol(bot, update):
"""Send a message when the command /vol is issued."""
volCallJson = requests.get("https://min-api.cryptocompare.com/data/generateAvg?fsym=EOS&tsym=USD&e=Kraken").json()
vol_name = (volCallJson)
volOut = volCallJson
update.message.reply_text(volOut)
and this is what sends it to user
dp.add_handler(CommandHandler("eosvol", eosvol))
i would like to select parts of the json data but i get errors like
vol_name = volCallJson()
TypeError: 'dict' object is not callable
or
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 dict
i understand im not accessing the json correctly. im just not sure how to do so.

Categories

Resources