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
# Ваш 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-запроса
try
response = HTTP.get(url);
catch err;
println("Введите Ваш API токен!")
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.
# Проверка ввода токена
if isdefined(Main, :response)
# Проверка статуса ответа
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
else
println("Введите Ваш API токен!")
end
Next, we will print all the received JSON3 object:
# Проверка ввода токена
if isdefined(Main, :data)
println("$data")
else
println("Введите Ваш API токен!")
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.