10 API-интерфейсов погоды для разработчиков: комплексное руководство по интеграции данных о погоде

Вы разработчик и хотите интегрировать данные о погоде в свое приложение? Не смотрите дальше! В этой статье блога мы рассмотрим широкий спектр погодных API, которые предоставляют информацию о погоде в режиме реального времени и прогнозируют ее, что позволяет вам с легкостью создавать приложения, ориентированные на погоду. Так что возьмите свой любимый напиток для кодирования, расслабьтесь и приступим!

  1. API OpenWeatherMap:

    import requests
    API_KEY = "your_api_key"
    url = f"http://api.openweathermap.org/data/2.5/weather?q=city_name&appid={API_KEY}"
    response = requests.get(url)
    data = response.json()
    # Access weather information from the data
    temperature = data['main']['temp']
    description = data['weather'][0]['description']
  2. API Weatherbit:

    const fetch = require('node-fetch');
    const API_KEY = 'your_api_key';
    const url = `https://api.weatherbit.io/v2.0/current?city=city_name&key=${API_KEY}`;
    fetch(url)
     .then(response => response.json())
     .then(data => {
       const temperature = data.data[0].temp;
       const description = data.data[0].weather.description;
     });
  3. API AccuWeather:

    import okhttp3.OkHttpClient;
    import okhttp3.Request;
    import okhttp3.Response;
    import org.json.JSONArray;
    import org.json.JSONObject;
    OkHttpClient client = new OkHttpClient();
    String apiKey = "your_api_key";
    String url = "http://dataservice.accuweather.com/forecasts/v1/daily/1day/city_name?apikey=" + apiKey;
    Request request = new Request.Builder()
       .url(url)
       .build();
    Response response = client.newCall(request).execute();
    String jsonData = response.body().string();
    JSONObject data = new JSONObject(jsonData);
    JSONArray forecasts = data.getJSONArray("DailyForecasts");
    double temperature = forecasts.getJSONObject(0).getJSONObject("Temperature").getJSONObject("Minimum").getDouble("Value");
    String description = forecasts.getJSONObject(0).getString("Day").getString("LongPhrase");
  4. WeatherAPI.com:

    require 'net/http'
    require 'json'
    api_key = 'your_api_key'
    url = URI("https://api.weatherapi.com/v1/current.json?key=#{api_key}&q=city_name")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    request = Net::HTTP::Get.new(url)
    response = http.request(request)
    data = JSON.parse(response.body)
    temperature = data['current']['temp_c']
    description = data['current']['condition']['text']
  5. Climacell API:

    $apiKey = 'your_api_key';
    $url = "https://api.climacell.co/v3/weather/realtime?lat=latitude&lon=longitude&apikey={$apiKey}";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    $temperature = $data['temp']['value'];
    $description = $data['weather_code']['value'];
  6. API Dark Sky (теперь часть приложения Apple Weather):

    import requests
    API_KEY = 'your_api_key'
    url = f"https://api.darksky.net/forecast/{API_KEY}/latitude,longitude"
    response = requests.get(url)
    data = response.json()
    temperature = data['currently']['temperature']
    description = data['currently']['summary']
  7. API Weather Underground:

    const fetch = require('node-fetch');
    const API_KEY = 'your_api_key';
    const url = `http://api.wunderground.com/api/${API_KEY}/conditions/q/country_code/city_name.json`;
    fetch(url)
     .then(response => response.json())
     .then(data => {
       const temperature = data.current_observation.temp_c;
       const description = data.current_observation.weather;
     });
  8. API визуального пересечения:

    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.Scanner;
    String apiKey = "your_api_key";
    String url = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/city_name?unitGroup=us&key=" + apiKey;
    URL apiUrl= new URL(url);
    HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();
    connection.setRequestMethod("GET");
    int responseCode = connection.getResponseCode();
    if (responseCode == 200) {
       Scanner scanner = new Scanner(connection.getInputStream());
       String jsonData = scanner.useDelimiter("\\A").next();
       scanner.close();
       JSONObject data = new JSONObject(jsonData);
       JSONArray days = data.getJSONArray("days");
       double temperature = days.getJSONObject(0).getDouble("temp");
       String description = days.getJSONObject(0).getString("conditions");
    }
  9. API WeatherStack:

    require 'net/http'
    require 'json'
    api_key = 'your_api_key'
    url = URI("http://api.weatherstack.com/current?access_key=#{api_key}&query=city_name")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = false
    request = Net::HTTP::Get.new(url)
    response = http.request(request)
    data = JSON.parse(response.body)
    temperature = data['current']['temperature']
    description = data['current']['weather_descriptions'][0]
  10. API Метеостата:

    $apiKey = 'your_api_key';
    $url = "https://api.meteostat.net/v2/stations/nearby?lat=latitude&lon=longitude&limit=1&key={$apiKey}";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    $station = $data['data'][0]['id'];
    $stationUrl = "https://api.meteostat.net/v2/observations/current?station={$station}&key={$apiKey}";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $stationUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    $temperature = $data['data'][0]['temperature'];
    $description = $data['data'][0]['weather']['summary'];

Вот и все! Это всего лишь несколько примеров API погоды, которые вы можете использовать для получения данных о погоде в своих приложениях. Каждый API имеет свои собственные функции, документацию и ограничения на использование, поэтому обязательно изучите каждый из них, чтобы найти тот, который лучше всего соответствует вашим потребностям.

Помните, что включение данных о погоде в ваше приложение может улучшить взаимодействие с пользователем и предоставить ценную информацию. Так что вперед, экспериментируйте и создавайте погодные приложения, которые будут информировать ваших пользователей и готовить их к любым погодным условиям!