Getting data from the OpenWeatherMap public API
This example describes the process of obtaining data from a public
API for a publicly available source of open data, the OpenWeatherMap weather service.
Introduction
[OpenWeatherMap](https://openweathermap.org /) uses a paid API (there is functionally limited free access) to provide current weather data, forecasts, and maps with weather events such as clouds, wind, pressure, and precipitation.
All weather data can be obtained in [JSON, XML or HTML] formats2.
In this example, we will use free access to the service to demonstrate the capabilities and tools of such work.
Getting started
Working with the Julia API can be done using
the HTTP package.jl, which provides convenient functions for sending
HTTP requests and response processing.
First, we'll install the HTTP libraries.jl and JSON3.jl for working with JSON data:
import Pkg; Pkg.add(["HTTP", "JSON3"]);
Sending a GET request
Now let's write the code to send a GET request to the OpenWeatherMap API.:
For the program to work, you need to specify in the variable
api_keyyour API token for accessing the service.
using HTTP, JSON3
# Your API key from OpenWeatherMap
api_key = "enter your API token";
# City of interest
city = "Moscow,ru";
# Request URL
url = "http://api.openweathermap.org/data/2.5/weather?q=$city&APPID=$api_key&units=metric";
# Sending a GET request
try
response = HTTP.get(url);
catch err;
println("Enter your API token!")
end
Here we use HTTP.get(url) to send a GET request to the API.
Extracting the received data
Now we check the response status: if the status is 200, then the request is successful.
Next, we use the function JSON3.read(response.body) for parsing the JSON response.
This is how we extract and output weather information from the received data.
# Checking the token input
if isdefined(Main, :response)
# Checking the response status
if response.status == 200
# Parsing the JSON response
data = JSON3.read(response.body)
# Extracting and outputting weather information
println("Today: $(Date(now()))")
println("Weather in the city $(data.name ):")
println("Temperature: $(data.main.temp)°C")
println("Humidity: $(data.main.humidity)%")
println("Description: $(data.weather[1].description)")
else
println("Request error: status $(response.status)")
end
else
println("Enter your API token!")
end
Next, we will print all the received JSON3 object:
# Checking the token input
if isdefined(Main, :data)
println("$data")
else
println("Enter your API token!")
end
This data is available for use as part of free access to the OpenWeatherMap service.
Conclusion
This is a basic example of working with the API for obtaining data from open sources
in Engee. Depending on the specific API you are working with,
You may need to adapt the code to handle different
types of requests and responses.