Чтобы получить данные о погоде с помощью API OpenWeather, вам понадобится ключ API. Вот несколько методов на разных языках программирования вместе с примерами кода:
-
Python:
import requests api_key = 'YOUR_API_KEY' url = f'http://api.openweathermap.org/data/2.5/weather?q=London&appid={api_key}' response = requests.get(url) data = response.json() # Accessing weather information temperature = data['main']['temp'] humidity = data['main']['humidity'] weather_description = data['weather'][0]['description'] print(f'Temperature: {temperature}K') print(f'Humidity: {humidity}%') print(f'Weather Description: {weather_description}') -
JavaScript (Node.js):
const axios = require('axios'); const api_key = 'YOUR_API_KEY'; const url = `http://api.openweathermap.org/data/2.5/weather?q=London&appid=${api_key}`; axios.get(url) .then(response => { const data = response.data; // Accessing weather information const temperature = data.main.temp; const humidity = data.main.humidity; const weather_description = data.weather[0].description; console.log(`Temperature: ${temperature}K`); console.log(`Humidity: ${humidity}%`); console.log(`Weather Description: ${weather_description}`); }) .catch(error => { console.log(error); }); -
Java:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class WeatherAPIExample { public static void main(String[] args) { String apiKey = "YOUR_API_KEY"; String url = "http://api.openweathermap.org/data/2.5/weather?q=London&appid=" + apiKey; try { URL obj = new URL(url); HttpURLConnection connection = (HttpURLConnection) obj.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // Accessing weather information // Parse JSON response here } catch (IOException e) { e.printStackTrace(); } } }
В этих примерах показано, как отправить запрос к API OpenWeather и получить информацию о погоде с помощью Python, JavaScript (Node.js) и Java. Не забудьте заменить 'YOUR_API_KEY'своим фактическим ключом API.