Parsing a JSON string and store in a variable - python

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")

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.

How to Itreate through Json

I need [0] to increase everytime and fetch the data when index change. from 0 to 13
import requests as r
import json
url = "https://services6.arcgis.com/bKYAIlQgwHslVRaK/arcgis/rest/services/CasesByRegion_ViewLayer/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json"
response = urlopen(url)
Data= json.load(response )
for index in Data:
list = Data['features'][0]['attributes']
[0]+1
print(list)
Here is another simple approach without using urllib:
import requests as r
import json
url = "https://jsonplaceholder.typicode.com/todos/1"
response = r.get(url)
data = response.json()
print(data)
requests.get().json() delivers the complete dict from the response payload:
import requests as r
response = r.get(url)
Data = response.json()
Your json.load() doesn't work as expected because response is a dictionary from the requests module, containing some HTTP stuff like status code, reason, encoding. For API calls, this is not what you want (HTTP errors should be handled with exceptions). What you want is response.json() or response.text.
Also, you imported requests but didn't use it? I don't know about urlopen(). Use requests.get().

How to save output of Python API call to file

new to coding so apologies for the basic q.
I am working with an API for a cyber security tool - Virus Total. I am trying to write a program that will call the API to get the report of the IP address, and then save that report to a file. I would like each API call to be saved in a separate file with a different name (with the format 'report[number of report]-[DDMMYYYY].txt'
I have tried to accomplish this with the open and write commands, but I am getting error: TypeError: write() argument must be str, not bytes
I have successfully got the API response but I do not know how to save it to a file with an automatically changing filename.
Any ideas?
I will post my code below (with my API key redacted).
Thanks
url = "https://www.virustotal.com/api/v3/ip_addresses/192.169.69.25"
headers = {
"Accept": "application/json",
"x-apikey": "REDACTED"
}
response = requests.request("GET", url, headers=headers)
with open("testoutput1.txt", "w") as f:
f.write(response)
This is very late, so you likely already have this solved, but for future searches, you likely want to save the json response (f.write(response.json())) or raw text (f.write(response.text)) rather than the response directly, which is what the TypeError: write() argument must be str, not bytes is indicating.
Here is an example with minor changes to use pathlib and format the filename based on your request:
import json
from datetime import datetime
from pathlib import Path
import requests
url = "https://catfact.ninja/fact"
headers = {
"Accept": "application/json",
}
response = requests.request("GET", url, headers=headers)
# # As a tip, breakpoint can be very helpful when debugging. Try:
# breakpoint()
idx = 1 # Hypothetical index from a for-loop
date = datetime.now().strftime("%d%m%Y")
Path(f"report{idx}-{date}.json").write_text(json.dumps(response.json()))
As a side-note, with Python 3.10, you can now get a much more helpful error message: TypeError: write() argument must be str, not Response

How to get JSON response in Python?

I've been trying to get JSON response out of the following code, but it's throwing an error
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
for item in response:
print(item, response[item])
I wanna print the JSON in the following format:
https://i.stack.imgur.com/ZWMbr.png
your code works well to get the correct respone from the url. The problem is that you should parse the raw respone as the json format. Please refer to the following code:
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
# dump response into json
result = response.content.decode('utf-8')
result = json.loads(result)
print(result) # print raw json
# print as key-value pairs
for item in result:
print("{0} : {1}".format(item, result[item]))
The output is like following:
Example output
I think you're misunderstanding what the response contains.
Your initial code is good.
from requests import get
import json
url = "https://api.wheretheiss.at/v1/satellites/25544"
response = get(url)
You now have a response. see here for more info.
In this response you have status_code, content, encoding, and the response content as text. it also contains other information about the request. eg we don't want to continue if the request failed
You can simply parse the json by calling json.loads on the decoded response via response.text
parsed_json = json.loads(response.text)
or
parsed_json = response.json()
for item in json_:
print(item, json_[item])
I hope it helps. it is also duplicate to HTTP requests and JSON parsing in Python

Object is not subscriptable while filtering a GET request

I am using requests on python to receive data from the twitch api. However, I only want some of the data, not all of it. I only want the is_live parenthisis. However, I am trying to do this by using:
final = response["is_live"]
This returns me the error:
TypeError: 'Response' object is not subscriptable
Is there a different way to filter the Get data?
Thanks, I will leave my code below:
import requests
headers = {
'client-id': 'myclientid',
'Authorization': 'my authorisation',
}
params = (
('query', 'Ninja'),
)
response = requests.get('https://api.twitch.tv/helix/search/channels', headers=headers, params=params)
final = response["is_live"]
print(final)```
get method returns Response object. You need to apply "filtering" on text field of it:
response = requests.get('https://api.twitch.tv/helix/search/channels', headers=headers, params=params)
final = response.text["is_live"]

Categories

Resources