Polling the Weather
An excerpt from Automate Your Home Using Go by Ricardo Gerardi and Mike Riley
In order to query the current weather conditions, we need access to an API that can provide those details. Fortunately, a service called OpenWeather offers a free tier for developers that allows a copious number of calls to their service. Sign up to request a free API key. You will need this key when making calls to OpenWeather’s API. In particular, it will be used to poll the current outdoor temperature in your area.
Once you have your free OpenWeather API key, test it out by polling the current temperature in your area with this small Go program, which uses the openweathermap
package to query the OpenWeather API. Replace the API_KEY
and ZIP_CODE
values with your own before running the test. If you live outside the United States, replace the country code as well:
package main
import (
"fmt"
"log"
"os"
owm "github.com/briandowns/openweathermap"
)
func main() {
w, err := owm.NewCurrent("F", "EN", API_KEY)
if err != nil {
log.Fatalln(err)
}
w.CurrentByZip(ZIP_CODE, "US")
fmt.Println(w.Main.Temp)
}
Save the file as openweathertest.go
and run go mod tidy
to download GitHub user Brian Downs’ openweathermap
Go library. This library makes it very easy to use OpenWeather’s API in the Go language environment.
With everything nice and tidy, run the program using the usual Go run syntax to test your API key, like this:
$ go run openweathertest.go
Assuming the values you replaced for your API_KEY
and ZIP_CODE
are valid, you should see the current temperature output in Fahrenheit. If you prefer the temperature scale be reported in Celsius, change the parameter in NewCurrent
to C
, like this:
w, err := owm.NewCurrent(“C”, “EN”, API_KEY)
Congratulations! You now are able to poll the current outdoor temperature in your area. The OpenWeather API offers many other options you can explore. The free tier is somewhat limited in the level of detail and forecast information it provides, but enough data is available to be useful for our project. Feel free to experiment with other calls to the API, as well as poll other geographic regions where you might be interested in the current temperature.
We hope you enjoyed this excerpt from Automate Your Home Using Go by Ricardo Gerardi and Mike Riley. You can purchase the ebook, now in beta, directly from The Pragmatic Bookshelf: