I am trying to parse json data from a site that shows values of crypto currency. I am trying to parse it using python. I am a little lost on how to show the output.
API: https://min-api.cryptocompare.com/data/price?fsym=XMR&tsyms=USD
# code starts below
import requests
# Set the request parameters
url = 'https://min-api.cryptocompare.com/data/price?fsym=XMR&tsyms=USD'
# Fetch url
print("Fetching url..")
# Do the HTTP get request
response = requests.get(url, verify=True) #Verify is check SSL certificate
# Error handling
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
# Decode the JSON response into a dictionary and use the data
USD = response.json()
output = USD[0]['USD']
print('Output USD:'), USD
# code ends
I am getting a response code 200 because IDLE tries to exit. The code is based off another project and I don't believe I am parsing json correctly?
The problem is here:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
The way you've indented, Python will always call exit(). You want it to call exit() only if there was actually an error, like so:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
However, you have another problem. You're trying to assign "output" the value of an object in USD; USD doesn't exist:
data = response.json()
output = USD[0]['USD'] #"USD" doesn't exist. It's the value you're trying to find, not the json that contains the object itself.
print('Output USD:'), USD #"USD" doesn't exist. I think you meant to print "output" here, which is the value you're setting in the line above.
Instead, try this:
data = response.json()
output = data["USD"]
print('Output USD:'), output
Your exit() line is not indented correctly. Try this:
if response.status_code != 200:
print('Status:', response.status_code, 'Problem with the request. Exiting.')
exit()
Additionally, even though you are parsing the JSON correctly, you incorrectly use the resulting data. Try this:
output = USD['USD'] # Note: "[0]" not required
print('Output USD:', USD) # Note: ", USD" inside the parentheses
Related
I need to print all requests from specific Postman collection. I have this code:
import requests
# Set up Postman API endpoint and authorization
postman_api_endpoint = "https://api.getpostman.com/collections"
postman_api_key = "PMAK-63b6bf724ebf902ad13d4bf2-e683c12d426716552861acda**********"
headers = {"X-Api-Key": postman_api_key}
# Get all requests from Postman collection
collection_id = "25184041-c1537769-f598-4c0e-b8ae-8cd185a79c03"
response = requests.get(f"{postman_api_endpoint}/{collection_id}/items", headers)
if response.status_code != 200:
print("Error retrieving collection:", response.text)
else:
# Print all requests
requests_data = response.json()["items"]
for request_data in requests_data:
request_method = request_data["request"]["method"]
request_url = request_data["request"]["url"]
request_headers = request_data["request"]["header"]
request_body = request_data["request"]["body"]["raw"] \
if request_data["request"]["body"]["mode"] == "raw" else ""
print(f"{request_method} {request_url}")
print("Headers:")
for header in request_headers:
print(f"{header['key']}: {header['value']}")
print("Body:")
print(request_body)
I received an error while I try to call response.text and have such massage:
Error retrieving collection: {"error":{"name":"notFound","message":"Requested resource not found"}}
Which means that I have 404 error. I have several assumptions what I did wrong:
I entered incorrect api key(But I checked several times and regenerated it twice)
I entered incorrect collection id, but in the screen below you can see where I took it and it is correct
And as I think the most likely variant I wrote incorrect request where I put my key and my collection id(I din't find any example how such requests should be like)
And of course I have requests in my collection, so error can not be because the collection is empty
Please give me some advice how I can fix this error. Thank you!
The answer is actually is really simple. I didn't know that I need to push button save request in Postman. I think if I create request in collection it will automatically save it. But I didn't, so I just saved all requests manually and finally receive correct response.
As I cannot see any reference on how to use properly the sysparm_query_category, may I confirm on how did you append the sysparm_query_category in get request?
Added below line of codes. I hope someone can help and guide me as I'm new to ServiceNow. Thanks!
from pysnow import Client
...
resource = self.client.resource(api_path=F"/table/{table}")
resource.parameters.add_custom({"sysparm_query_category": "cat_read_generic"})
request = resource.get(query=query, fields=fields)
https://developer.servicenow.com/dev.do#!/reference/api/sandiego/rest/c_TableAPI
I am not aware pysnow API. I hope this helps. Else refer to the comment above.
#Need to install requests package for python
#easy_install requests
import requests
# Set the request parameters
url = 'https://demonightlycoe.service-now.com/api/now/table/incident?sysparm_query=category%3Dcat_read_generic&sysparm_limit=1'
# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'
# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Do the HTTP request
response = requests.get(url, auth=(user, pwd), headers=headers )
# Check for HTTP codes other than 200
if response.status_code != 200:
print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
exit()
# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)
Upon checking and testing, we can use the add_custom
client.parameters.add_custom({'foo': 'bar'})
that would be additional to the parameters like &foo=bar
https://pysnow.readthedocs.io/en/latest/usage/parameters.html
I am trying to adapt this script so that even if multiple messages are sent at the same time the script will just keep trying until they are let through.
The original script is: https://github.com/4rqm/dhooks
My version is:
def post(self):
"""
Send the JSON formated object to the specified `self.url`.
"""
headers = {'Content-Type': 'application/json'}
result = requests.post(self.url, data=self.json, headers=headers)
if result.status_code == 400 or result.status_code == 429:
print(result.status_code)
#its the line below that does not work.
post(self)
else:
print("Payload delivered successfuly")
print("Code : "+str(result.status_code))
time.sleep(2)
I have a script that runs and submits urls in a text file via GET to an API and saves the response to a text file. However, the for loop quits if I get a failure in the first section and does not continue passing the others. How can I still grab the failure and continue on with the others without the script exiting before it finishes?
sys.stdout=open("mylog.txt","w")
for row in range(0, len(exampleData)):
url = exampleData[row][0]
print (url)
response = requests.get(url, auth=(user, pwd))
if response.status_code != 200:
print('Failure Message {}' .format(response.text))
work = 'failed'
continue
data = json.loads(response.text)
print(data)
work = 'succeeded'
sys.stdout.close()
Use continue instead of exit()
Use an exception to catch the failure and continue on.
Now that your loop control is corrected, it must be working correctly. It will print out a failure message every time it gets an error response (not 200). If you're only seeing one error message, you're only getting one non-200 response from the other side. If that's not what you expect, the problem is on the server side. (Or in the contents of exampleData.)
You need to debug your own server-client system. Simplify this loop so that the only thing it does is print diagnostic information about the response (e.g., print status_code), and find out what's really going on.
I am currently writing a script that sends a request to a specific webpage and returns a JSON response. The issue is that multiple of the same requests come back, and some are HTML and one is JSON. I've been researching how to keep checking until a valid JSON response is returned, but no luck. Here is what I have currently:
response = requests.get('http://www.samplewebpage.com')
inputJSON = json.loads(response.text)
exampleList = list(inputJSON['metaData'].values())
outputArray = []
Is there an easy way to loop through the json.loads to wait until the response is a actual JSON?
Thanks in advance.
found = False
while not found:
response = requests.get('URL')
try:
inputJSON = json.loads(response.text)
found = True
print('valid JSON')
except:
print('not valid JSON')
pass