I'm trying to get this api request and have it formatted when I dump it into the JSON file. Whenever I do, its all one string and very hard to read. I've tried adding the indent but it didn't do anything. I can provide the API key if needed.
import json, requests
url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={APIKEY}"
response = requests.get(url)
response.raise_for_status()
with open('weather.json', 'w') as outfile:
json.dump(response.text, outfile, indent=4)
There are a couple problems with your code, I think.
First of all, it's considered better form to write unrelated imports on separate lines instead of separated by a comma. We generally only use commas when doing things like from module import thing1, thing2
.
I'm assuming you left {APIKEY}
in the URL as a placeholder, but just in case: you will need to insert your API key there. You can do this with a .format
call as-is.
You call response.raise_for_status()
. This ought to be wrapped in a try/except block since if the request fails, this raises an exception. Your code will just barf and you'll be SOL at that point.
But here's the most important thing: the response.text
is a string. json.dump
only works with dictionaries. You'll need a dictionary, so use response.json()
to get it. (Alternatively, if you wanted to manipulate the JSON first, you could get it from the string by doing json_string = json.loads(response.text)
.)
Here's what it should probably come out to:
import json
import requests
# Replace this with your API key.
api_key = '0123456789abcdef0123456789abcdef'
url = ("http://api.openweathermap.org/data/2.5/forecast/city?"
"id=524901&APPID={APIKEY}".format(APIKEY=api_key))
response = requests.get(url)
try:
response.raise_for_status()
except requests.exceptions.HTTPError:
pass
# Handle bad request, e.g. a 401 if you have a bad API key.
with open('weather.json', 'w') as outfile:
json.dump(response.json(), outfile, indent=4)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With