Search code examples
rustopenweathermap

I am trying to get data over an OpenWeather API in Rust but I am facing some iusse regarding parsing I guess


extern crate openweather;
use openweather::LocationSpecifier;
static API_KEY: &str = "e85e0a3142231dab28a2611888e48f22";

fn main() {
    let loc = LocationSpecifier::Coordinates {
        lat: 24.87,
        lon: 67.03,
    };
    let weather = openweather::get_current_weather(loc, API_KEY).unwrap();

    print!(
        "Right now in Minneapolis, MN it is {}K",
        weather.main.humidity
    );
}

error : thread 'main' panicked at 'called Result::unwrap() on an Err value: ErrorReport { cod: 0, message: "Got unexpected response: \"{\\"coord\\":{\\"lon\\":67.03,\\"lat\\":24.87},\\"weather\\":[{\\"id\\":803,\\"main\\":\\"Clouds\\",\\"description\\":\\"broken clouds\\",\\"icon\\":\\"04n\\"}],\\"base\\":\\"stations\\",\\"main\\":{\\"temp\\":294.15,\\"pressure\\":1018,\\"humidity\\":60,\\"temp_min\\":294.15,\\"temp_max\\":294.15},\\"visibility\\":6000,\\"wind\\":{\\"speed\\":5.1,\\"deg\\":30},\\"clouds\\":{\\"all\\":70},\\"dt\\":1574012543,\\"sys\\":{\\"type\\":1,\\"id\\":7576,\\"country\\":\\"PK\\",\\"sunrise\\":1573955364,\\"sunset\\":1573994659},\\"timezone\\":18000,\\"id\\":1174872,\\"name\\":\\"Karachi\\",\\"cod\\":200}\"" }


Solution

  • The issue is a JSON parsing error due to the deserialized struct not matching OpenWeather's JSON, perhaps the API recently added this? With your example, the OpenWeatherCurrent struct is missing timezone.

    But it looks like there is an open PR that will fix this, you can test it by doing the following:

    • Change your Cargo.toml dependency to openweather = { git = "https://github.com/caemor/openweather" }.
    • The PR author has also updated the get_current_weather signature so you'll need to change lines 2, 10 to the following:

      use openweather::{LocationSpecifier, Settings};
      
      let weather = openweather::get_current_weather(&loc, API_KEY, &Settings::default()).unwrap();