Obtaining data from the public API OpenWeatherMap¶
This example describes the process of obtaining data from the public API of the OpenWeatherMap weather service. API of a publicly available source of open data - OpenWeatherMap weather service.
Introduction¶
OpenWeatherMap uses a paid API (there is functionally limited free access) to provide current weather data, forecast and maps with weather phenomena such as clouds, wind, pressure and precipitation. All weather data can be retrieved in JSON, XML or HTML formats. In this example, we will use the 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.jl package, which provides convenient functions for sending HTTP requests and processing responses. HTTP requests and processing the responses.
First, let's install the HTTP.jl and JSON3.jl libraries 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 programme to work you need to specify in the variable
api_key
your API token to access the service.
using HTTP, JSON3
# Ваш API ключ от OpenWeatherMap
api_key = "введите Ваш API токен";
# Интересующий город
city = "Moscow,ru";
# URL для запроса
url = "http://api.openweathermap.org/data/2.5/weather?q=$city&APPID=$api_key&units=metric";
# Отправка GET-запроса
response = HTTP.get(url);
Here we use HTTP.get(url)
to send a GET request to the API.
Retrieving the received data¶
Now we check the status of the response: if the status is 200, then the request is successful.
Next, we use the JSON3.read(response.body)
function to parsing the JSON response.
In this way we extract and output weather information from the received data.
# Проверка статуса ответа
if response.status == 200
# Парсинг JSON-ответа
data = JSON3.read(response.body)
# Извлечение и вывод информации о погоде
println("Сегодня: $(Date(now()))")
println("Погода в городе $(data.name):")
println("Температура: $(data.main.temp)°C")
println("Влажность: $(data.main.humidity)%")
println("Описание: $(data.weather[1].description)")
else
println("Ошибка при запросе: статус $(response.status)")
end
Next, we print the entire received JSON3
object:
println("$data")
These data are available for work within free access to the OpenWeatherMap service.
Conclusion¶
This is a basic example of working with the API to retrieve 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.