Rust で Web API を叩く
環境
$ cargo versioncargo 1.45.0 (744bd1fbb 2020-06-15)
$ rustc --versionrustc 1.45.0 (5c1f21c3b 2020-07-13)
依存関係
-
HTTP クライアントの
reqwest
の crate を使う -
Cargo.toml
には以下のように記載[dependencies]reqwest = { version = "0.10", features = ["json"] }tokio = { version = "0.2", features = ["full"] }
使い方
-
とりあえず GET して Body を取得してみる
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> {let res = reqwest::get("https://www.google.co.jp/").await?.text().await?;println!("{:?}", res);Ok(())} -
POST するときは以下のように:
let client = reqwest::Client::new();let res = client.post("http://httpbin.org/post").body("the exact body that is sent").send().await?;
reqwest
をモックする
こんなのもあるらしい
-
reqwest
の軽量クレート:ureq