Build a command-line weather app in Rust with reqwest and OpenWeatherMap

This post builds a small interactive CLI in Rust: type a city name, get the current temperature and conditions from the OpenWeatherMap current weather API. It uses reqwest for HTTP and serde to deserialize the JSON response into structs.
You’ll need a free OpenWeatherMap account and API key. New keys can take a while to activate, so create one before you start.
Set up the project
Section titled “Set up the project”cargo new weather_forecast_clicd weather_forecast_clicargo add reqwest --features blocking,json,querycargo add serde --features deriveAt the time of this update that produced:
[dependencies]reqwest = { version = "0.13.5", features = ["blocking", "json", "query"] }serde = { version = "1.0.229", features = ["derive"] }The features matter:
blockingenablesreqwest::blocking, a synchronous client, so you don’t need an async runtime for a simple CLI.jsonenables.json::<T>()on responses.queryenables.query(...)on requests, which URL-encodes parameters for you. In reqwest 0.13 this is an opt-in feature.deriveonserdeenables#[derive(Deserialize)].
Model the response
Section titled “Model the response”The current weather endpoint returns a lot of fields. You only need to declare the ones you use; serde ignores the rest.
{ "name": "Toronto", "main": { "temp": 4.2, "feels_like": 0.9, ... }, "weather": [{ "description": "light rain", ... }], ...}The full program
Section titled “The full program”Replace src/main.rs with:
use serde::Deserialize;use std::io::{self, Write};
#[derive(Debug, Deserialize)]struct WeatherData { name: String, main: Main, weather: Vec<Weather>,}
#[derive(Debug, Deserialize)]struct Main { temp: f32, feels_like: f32,}
#[derive(Debug, Deserialize)]struct Weather { description: String,}
const API_URL: &str = "https://api.openweathermap.org/data/2.5/weather";
fn fetch_weather_data( client: &reqwest::blocking::Client, api_key: &str, location: &str,) -> Result<WeatherData, reqwest::Error> { client .get(API_URL) .query(&[("q", location), ("units", "metric"), ("appid", api_key)]) .send()? .error_for_status()? .json::<WeatherData>()}
fn display_weather_data(data: &WeatherData) { println!("Current weather for {}:", data.name); println!(" Temperature: {:.1} °C", data.main.temp); println!(" Feels like: {:.1} °C", data.main.feels_like); if let Some(weather) = data.weather.first() { println!(" Conditions: {}", weather.description); }}
fn main() { let api_key = std::env::var("OPENWEATHER_API_KEY") .expect("set the OPENWEATHER_API_KEY environment variable"); let client = reqwest::blocking::Client::new();
loop { print!("Enter location (or 'quit'): "); io::stdout().flush().unwrap();
let mut input = String::new(); if io::stdin().read_line(&mut input).unwrap() == 0 { break; // EOF (Ctrl+D / Ctrl+Z) }
let location = input.trim(); if location.is_empty() { continue; } if location == "quit" { break; }
match fetch_weather_data(&client, &api_key, location) { Ok(data) => display_weather_data(&data), // without_url() keeps the API key (part of the URL) out of the error message. Err(err) => println!("Error fetching weather data: {}", err.without_url()), } }}A few things worth pointing out:
units=metricreturns Celsius. The default (standard) is Kelvin, andimperialis Fahrenheit..error_for_status()turns a 401 (bad or not-yet-active key) or 404 (unknown city) into anErr. Without it, reqwest would try to parse the error body asWeatherDataand you’d get a confusing deserialization error instead.- The API key comes from an environment variable instead of being hard-coded, so it doesn’t end up in your Git history.
weatheris an array;.first()avoids a panic if it’s ever empty, which indexing with[0]would not.
Run it
Section titled “Run it”export OPENWEATHER_API_KEY=your_key_here # PowerShell: $env:OPENWEATHER_API_KEY = "your_key_here"cargo runEnter location (or 'quit'): TorontoCurrent weather for Toronto: Temperature: 4.2 °C Feels like: 0.9 °C Conditions: light rainThe q parameter takes a city name, optionally followed by a country code (London,GB), or for US locations a state and country code (Portland,OR,US). Adding the country code avoids getting the wrong city when names collide.
Gotchas and next steps
Section titled “Gotchas and next steps”- City-name lookup is deprecated. OpenWeatherMap’s docs say requests by city name, ZIP code and city ID are deprecated: they still work but no longer get fixes. The recommended approach is to resolve the name to coordinates with the Geocoding API and then call the weather endpoint with
latandlon. - This only shows current conditions. For forecasts, look at the 5 day / 3 hour forecast API, which uses the same response style.
- Don’t use
reqwest::blockinginside async code. If you later move this into a Tokio application, switch to the asyncreqwest::Client; the blocking client panics if called from within an async runtime.
Further reading
Section titled “Further reading”© 2026 David Li · Home · Blog · RSS ·Classic site · Built with Astro, Starlight and three.js · Logos:Font Awesome Free (CC BY 4.0)