Day 4:非同步 HTTP 請求(reqwest)

學習目標

  • 用 reqwest 發送 async HTTP 請求
  • 處理 JSON 回應
  • 建立第一個網路 client

今日重點

安裝

[dependencies]
tokio = { version = "1", features = ["full"] }
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }

GET 請求

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let resp = reqwest::get("https://httpbin.org/ip").await?;
    let body = resp.text().await?;
    println!("Body: {}", body);
    Ok(())
}

解析 JSON

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct IpInfo {
    origin: String,
}

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let resp = reqwest::get("https://httpbin.org/ip").await?;
    let info: IpInfo = resp.json().await?;   // 反序列化
    println!("IP: {}", info.origin);
    Ok(())
}

練習

use serde::Deserialize;

#[derive(Deserialize, Debug)]
struct Todo {
    id: u32,
    title: String,
    completed: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 抓取 https://jsonplaceholder.typicode.com/todos/1 並印出
    let todo: Todo = reqwest::get("https://jsonplaceholder.typicode.com/todos/1")
        .await?
        .json()
        .await?;
    println!("{:?}", todo);
    Ok(())
}

若無法連外網,可改用 local mock 或直接練習 struct 解析。

自我檢查

  • 會用 reqwest 做 GET
  • 會用 serde + .json() 解析回應
  • 能定義 Deserialize struct
  • 建立一個簡單的 API client

深入連結

  • reqwest 官方文件