Blog

Build a Rust Client for Live Trend Data

Build a typed Rust client for the Trends API with reqwest and serde: one POST, a double-parsed envelope, error handling, and 261 real weekly points for rust.

Trends API team Published Data as of 2026-11-18

261 weekly Google Search points for rust, 2021 to 2026

A Rust client for the Trends API is one POST to https://api.trendsmcp.ai/api with a Bearer key, and the response needs two JSON parses: the envelope first, then the body string inside it. Three crates cover the whole job: reqwest with blocking, json, and native-tls features and default features off, serde with derive, and serde_json. The example in this tutorial wraps them in a small typed client that pulls a full time series and growth windows for one keyword. Pulled on November 18, 2026 through the same requests sent via curl and Python, the series for rust on Google Search returned 261 weekly points, from 48 on November 13, 2021 to 55 on November 7, 2026, with a peak of 100 on February 21, 2026. Growth over 3 months was -32.1 percent and over 12 months -14.06 percent. No first-party Rust crate exists, so this client is the integration.

One POST returns an envelope with a JSON string inside

Every call is the same shape: POST to https://api.trendsmcp.ai/api, an Authorization: Bearer YOUR_API_KEY header, and a JSON body with mode, keyword, and source. The body picks the tool. get_time_series returns dated points for one keyword. get_growth returns point-to-point growth over windows such as 3M and 12M. get_top_trends returns a live ranked board with no keyword. The full mode list and the 14 keyword sources sit in the data catalog, and the docs carry the same contract.

The response is an envelope, not the data. It always looks like {"statusCode": 200, "body": "..."}. The body is a JSON string, so parse it a second time before reading any result field. That second parse is the step most first clients miss. The response envelope page and the body parsing guide show the same shape in other languages.

{"mode": "get_time_series", "keyword": "rust", "source": "Google Search"}
{"mode": "get_growth", "keyword": "rust", "source": "Google Search", "percent_growth": ["3M", "12M"]}

Three crates cover the whole client

The client needs reqwest for HTTP, serde for typed structs, and serde_json for the two parses. The blocking feature keeps the example free of an async runtime. The json feature adds the .json() request helper. Versions below are the ones this tutorial compiled against: reqwest 0.13, serde 1, serde_json 1, under rustc 1.100.0.

[package]
name = "trends-client"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = { version = "0.13", features = ["blocking", "json", "native-tls"], default-features = false }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

The API key comes from the environment, never from source code. Set TRENDS_API_KEY before running anything. The key comes from the account page. There is no first-party crate to install: the Rust Trends API page confirms the contract is one POST plus serde_json. The reqwest docs and serde_json docs cover the two libraries used here.

Typed structs turn the envelope into rows

Four structs carry the whole exchange. Envelope holds the transport layer: a statusCode number and a body string. SeriesPoint holds one dated point. GrowthWindow holds one window of a growth answer. GrowthResponse holds the full growth answer. Serde ignores fields the structs do not declare, so each struct lists only what the example reads.

One field deserves attention. Google Search points in this pull carry no volume key at all: 0 of the 261 points had one. A plain Option<f64> would fail to deserialize, because serde treats a missing field as an error unless told otherwise. #[serde(default)] on volume makes the missing key parse as None. Sources that do return volume, such as Wikipedia page views, still parse into the same struct.

use serde::Deserialize;

#[derive(Deserialize)]
struct Envelope {
    #[serde(rename = "statusCode")]
    status_code: u16,
    body: String,
}

#[derive(Deserialize)]
struct ApiErrorBody {
    error: String,
    message: String,
}

#[derive(Deserialize, Debug)]
struct SeriesPoint {
    date: String,
    value: f64,
    #[serde(default)]
    volume: Option<f64>,
    keyword: String,
    source: String,
}

#[derive(Deserialize, Debug)]
struct GrowthWindow {
    period: String,
    growth: f64,
    direction: String,
    recent_date: String,
    baseline_date: String,
    recent_value: f64,
    baseline_value: f64,
}

#[derive(Deserialize, Debug)]
struct GrowthResponse {
    search_term: String,
    data_source: String,
    results: Vec<GrowthWindow>,
}

One client struct holds the key and the POST

TrendsClient keeps the key and the HTTP client in one place. new() reads TRENDS_API_KEY and fails fast when it is missing. post() sends the payload, reads the response as text, parses the envelope, checks statusCode, then parses the body string a second time. time_series() and growth() are thin wrappers that build the payload and convert the parsed body into typed structs. main() pulls the series for rust, prints the count with the first, last, and peak points plus the last three weeks, then prints the 3M and 12M growth windows.

use std::env;

const API_URL: &str = "https://api.trendsmcp.ai/api";

struct TrendsClient {
    key: String,
    http: reqwest::blocking::Client,
}

impl TrendsClient {
    fn new() -> Result<Self, TrendsError> {
        let key = env::var("TRENDS_API_KEY").map_err(|_| TrendsError::MissingKey)?;
        Ok(Self {
            key,
            http: reqwest::blocking::Client::new(),
        })
    }

    fn post(&self, payload: serde_json::Value) -> Result<serde_json::Value, TrendsError> {
        let resp = self
            .http
            .post(API_URL)
            .header("Authorization", format!("Bearer {}", self.key))
            .json(&payload)
            .send()?;
        let text = resp.text()?;
        let envelope: Envelope = serde_json::from_str(&text)?;
        if envelope.status_code != 200 {
            let err: ApiErrorBody = serde_json::from_str(&envelope.body)?;
            return Err(TrendsError::Api {
                code: err.error,
                message: err.message,
            });
        }
        // body is a JSON string, so parse it a second time.
        Ok(serde_json::from_str(&envelope.body)?)
    }

    fn time_series(&self, keyword: &str, source: &str) -> Result<Vec<SeriesPoint>, TrendsError> {
        let body = self.post(serde_json::json!({
            "mode": "get_time_series",
            "keyword": keyword,
            "source": source,
        }))?;
        Ok(serde_json::from_value(body)?)
    }

    fn growth(
        &self,
        keyword: &str,
        source: &str,
        windows: &[&str],
    ) -> Result<GrowthResponse, TrendsError> {
        let body = self.post(serde_json::json!({
            "mode": "get_growth",
            "keyword": keyword,
            "source": source,
            "percent_growth": windows,
        }))?;
        Ok(serde_json::from_value(body)?)
    }
}

fn main() -> Result<(), TrendsError> {
    let client = TrendsClient::new()?;

    let points = client.time_series("rust", "Google Search")?;
    let peak = points
        .iter()
        .max_by(|a, b| a.value.partial_cmp(&b.value).unwrap())
        .unwrap();
    println!("{} weekly points for rust", points.len());
    println!("first: {} -> {}", points[0].date, points[0].value);
    println!("last:  {} -> {}", points[points.len() - 1].date, points[points.len() - 1].value);
    println!("peak:  {} -> {}", peak.date, peak.value);
    for p in &points[points.len() - 3..] {
        println!("  {} {}", p.date, p.value);
    }

    let growth = client.growth("rust", "Google Search", &["3M", "12M"])?;
    for w in &growth.results {
        println!(
            "{}: {}% ({:.0} on {} vs {:.0} on {})",
            w.period, w.growth, w.recent_value, w.recent_date, w.baseline_value, w.baseline_date
        );
    }
    let _ = (growth.search_term, growth.data_source);
    Ok(())
}

Reading the response as text first, instead of calling .json() on it, keeps failures readable. When the server answers with something that is not JSON, the error says so with the body attached, instead of hiding behind a decode error. The ? operator converts both reqwest errors and serde_json errors into TrendsError through the From impls in the next section.

Errors split into transport, envelope, and API errors

Four variants cover every failure this client can see. MissingKey means the environment variable is absent. Http means the request never completed. Json means a response was not the JSON the code expected. Api means the API answered with a statusCode other than 200 and an error code inside the body string. The error codes come from the API reference: invalid_api_key for a bad or missing key, no_data when nothing matches the keyword on the source, missing_parameter for a missing field, invalid_source for a source the API does not serve, and monthly_limit_reached when the plan pool is used up. Limits and pricing sit on the pricing page, not in this tutorial.

use std::fmt;

#[derive(Debug)]
enum TrendsError {
    MissingKey,
    Http(reqwest::Error),
    Json(serde_json::Error),
    Api { code: String, message: String },
}

impl fmt::Display for TrendsError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TrendsError::MissingKey => write!(f, "set TRENDS_API_KEY first"),
            TrendsError::Http(e) => write!(f, "request failed: {e}"),
            TrendsError::Json(e) => write!(f, "bad JSON: {e}"),
            TrendsError::Api { code, message } => write!(f, "API error {code}: {message}"),
        }
    }
}

impl std::error::Error for TrendsError {}

impl From<reqwest::Error> for TrendsError {
    fn from(e: reqwest::Error) -> Self {
        TrendsError::Http(e)
    }
}

impl From<serde_json::Error> for TrendsError {
    fn from(e: serde_json::Error) -> Self {
        TrendsError::Json(e)
    }
}

The split matters for retries. Http failures are worth retrying. Api failures are not: a no_data answer stays a no_data answer until the keyword or the source changes. The statusCode check belongs in post(), not in each caller, so every mode gets the same mapping.

The numbers: 261 weekly points for rust, verified two ways

The numbers below are live, but the verification has a limit worth stating plainly. The code above compiled cleanly under rustc 1.100.0, with two dead-code warnings for struct fields the example never reads and no errors. The compiled binary did not complete a live call on this machine: this VM's egress proxy answers reqwest with a CloudFront 403 while curl and Python requests reach the API with identical payloads and the same key. So the API behavior was verified a second way, with the same requests sent through curl and Python, plus the kit's own Trends API tool. The values in this section come from those verified calls, pulled November 18, 2026.

Call Result
get_time_series, rust, Google Search 261 weekly points, Nov 13, 2021 to Nov 7, 2026
First point 48 on Nov 13, 2021
Latest point 55 on Nov 7, 2026
Peak 100 on Feb 21, 2026
Low 40 on Dec 18, 2021
Last three points 52, 54, 55 (Oct 24, Oct 31, Nov 7, 2026)
get_growth 3M -32.1 percent, 81 on Aug 8, 2026 to 55 on Nov 7, 2026
get_growth 12M -14.06 percent, 64 on Nov 8, 2025 to 55 on Nov 7, 2026

The program prints one line per fact, in this shape, filled with the verified values:

261 weekly points for rust
first: 2021-11-13 00:00:00+00:00 -> 48
last:  2026-11-07 00:00:00+00:00 -> 55
peak:  2026-02-21 00:00:00+00:00 -> 100
  2026-10-24 00:00:00+00:00 52
  2026-10-31 00:00:00+00:00 54
  2026-11-07 00:00:00+00:00 55
3M: -32.1% (55 on 2026-11-07 00:00:00+00:00 vs 81 on 2026-08-08 00:00:00+00:00)
12M: -14.06% (55 on 2026-11-07 00:00:00+00:00 vs 64 on 2025-11-08 00:00:00+00:00)

One caution on the keyword itself. The bare word rust mixes the language with other uses of the word, so the series above is not a pure language series. The Rust Trends API page shows the same split: rust programming is the cleaner language series, while bare rust scored 76 on Sep 5, 2026 against 14 for rust programming in an earlier pull. Use the exact token the question needs, and store each string as its own series.

Growth and series answer different questions

get_growth answers whether interest is rising or falling over a window. It compares two points and returns the percent change, so one call covers several windows at once: the example asks for 3M and 12M together. The default window is 12M when percent_growth is left out. Windows run from 7D up to 5Y, plus MTD, QTD, and YTD.

get_time_series answers what happened between those points. It returns every dated point, about five years of weekly history, so the caller can find the peak, spot a spike, or chart the line. The rust pull returned 261 points, which is five years of weeks. Growth says rust fell 32.1 percent in 3 months. The series adds the shape: the fall came after a peak of 100 on February 21, 2026, and the last three weeks flattened at 52, 54, and 55. Either call alone would hide half the story.

Common questions

Why do the series dates land on Saturdays?

Weekly points are dated to the Saturday that ends the week. The rust pull ran November 18, 2026 and the latest point was Saturday, November 7, 2026. The peak week ended Saturday, February 21, 2026.

What happens when a keyword has no data?

The API answers with statusCode 400 and an error code of no_data inside the body string. The client maps that to TrendsError::Api, so the caller sees the code instead of a JSON parse failure. Change the keyword or the source before retrying.

Sources