Skip to content
Sign UpLog In
This post is read-only. Explore Repls and connect with other creators on Community.View Community
The info in this post might be out of date, check out our docs instead. View docs
26

Weather API in Python

LeonDoesCode
LeonDoesCode

Difference

We just covered a tutorial on Using Web APIs in Python, where we got data from an API and displayed it. This time we are going to look at API Keys and how they are stored to keep them secure. We will also make a more useful application than the last one to see how the code can be used in a real project.

OpenWeatherMap

The API we will be using for this tutorial is OpenWeatherMap (OWM). It's free for current weather, and is similar to the data we are currently dealing with (JSON). So let's get started with this service!

First of all, you need to go to OWM's webiste. You should see a sign up button at the top. Once you have signed up, you should be on a page with the title "Members", if not, you can go to this link. Then head to the section called "API Keys", and you should see a long string of numbers and letters. This is your key.

To get more information on the specific part of the API we are using, you can look here.

Now, let's store that key securely.

API Key Secrecy

Why do we need our API Keys to be secret? We don't want others using our key to access data from an API. These API Keys are linked to us, so any behaviour which goes against your plan with the service, may lead to charges or being locked from the service.

To stop other who are viewing your Repl from knowing your API Key (Unless in Multiplayer), we use something called a .env file. These files contain Environment Variables, which can be used by your programs without being placed in the code.

So make a file called .env and inside write: APIKEY=(your api key). Replacing value with your API Key.

We can access our Environment Variables in Python using the os module. All we have to do is:

import os # Set apikey to the APIKEY in the environment variables apikey = os.environ["APIKEY"] # Print the key to check is works print(apikey)

Now we can start!

Let's Do This!

First, let's import the required modules:

import urllib.request import json import os import time

Next, we will get the apikey and set the url and add the necessary data to it:

# Set apikey to the APIKEY in the environment variables apikey = os.environ["APIKEY"] # Set the api endpoint to the OWM url url = "https://api.openweathermap.org/data/2.5/weather?" # Add our apikey to the url url += "APPID=" + apikey # Add the correct units and location to the url url += "&units=imperial&&q=Florida"

The apikey is defined in the Environment Variables file .env. We the set the endpoint url for the OWM API. Next we add our apikey to the url under APPID. Lastly, we add our location the url.

Now we are ready to request the data from the constructed url:

# Make our request and get the decoded data read from the request req = urllib.request.Request(url) resp = urllib.request.urlopen(req).read().decode() # Read the JSON data into a Python Data Type data = json.loads(resp)

Once we read the data, we decode it and convert from JSON into a Python Data Type, in this case a dict.

Lastly, we are going to make a little automatic script which tells us the current, min and max temperature and humidity at our location.

while True: # Make our request and get the decoded data read from the request req = urllib.request.Request(url) resp = urllib.request.urlopen(req).read().decode() # Read the JSON data into a Python Data Type data = json.loads(resp) # Get the data we need temp = data["main"]["temp"] tempmin = data["main"]["temp_min"] tempmax = data["main"]["temp_max"] humidity = data["main"]["humidity"] name = data["name"] # Prin out the data we are using print(f"It is currently {temp}°F in {name}.\nThe temperature will be {tempmax}°F lowest to {tempmin}°C highest.\nCurrent humidity sits at {humidity}%.") # Sleep for a minute before reloading the data time.sleep(60)

As you can see, we can now read the data like a normal dict in Python! This makes it super easy to work with.

Conclusion

You should now understand how to access APIs which use Keys and how we can implement data into a more serious application. Even though, this application is not very complicated. For a better use of APIs, have a look at

@bossotron13
's WeatherAPI. I hope you found this useful in your ventures with APIs!

Have a great day!

P.S
This tutorial was suggested by

@bossotron13
.
If you have any suggestions for tutorials, leave them in the comments and I'll be sure to have a look. If you like one in the comments, then give it an up vote to show that you want to see it. It makes my life so much more easier. Thanks in advance!

3 years ago

Voters

Comments

TopNew
1
Reuben123
Reuben123

Hey! This is great. Anyone know how can I get the current time from the API?

2 years ago
1
lyonsstephen
lyonsstephen

I'm having a problem with the beginning API, whenever I try to run the code to output the API key, the code crashes with this error,

Traceback (most recent call last):
File "main.py", line 7, in
APIKEY = os.environ["APIKEY"]
File "/usr/local/lib/python3.7/os.py", line 678, in getitem
raise KeyError(key) from None
KeyError: 'APIKEY'

Any Suggestions?

3 years ago
2
LeonDoesCode
LeonDoesCode

@lyonsstephen
In the .env file, did you capitalise the word APIKEY. If so, did you make sure not to include any spaces between the name, equal, and value? Like so: APIKEY=5738392927553744839....

3 years ago
1
TristanMisja
TristanMisja

GREAT tutorial! Can you do a tutorial on the datetime and time modules?

3 years ago
Load more