SteamのAPIからゲームタイトルのリストを取得して、標準出力に出力するプログラムを作った。
割と内容はしょうもない内容だと思う。
API URL
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
APIレスポンス
レスポンスとして、ネストした構造のJSONデータが取得できる。
出力例
{ "applist": { "apps": [ { "appid": 000000, "name": "ゲームタイトル" } ] } }
rustでの実装について
rustにはserdeというJSONデータを処理するためのライブラリがある。
rustでは、このライブラリを用いてJSONを処理するのがスタンダードらしい。
JSONを処理するには、構造体を定義する必要があるのだけど、
ネストしているJSONデータを扱う場合は、キーごとに構造体の定義が必要でその点が面倒だった。
実装例
Cargo.toml
使用したライブラリは下記の通り。
[dependencies] reqwest = { version = "0.10", features = ["json"] } tokio = { version = "0.2", features = ["full"] } serde = { version = "1.0", features = ["derive"] } serde_json = "1.0"
main.rs
use serde::{ Serialize, Deserialize }; #[derive(Serialize, Deserialize, Debug)] struct AppList { applist: Apps } #[derive(Serialize, Deserialize, Debug)] struct Apps { apps: Vec<Title>, } #[derive(Serialize, Deserialize, Debug)] struct Title { appid: u32, name: String, } #[tokio::main] async fn main() -> Result<(), reqwest::Error> { let api_url = String::from("http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json"); let response = reqwest::get(&api_url).await?; let values = serde_json::from_str::<AppList>(&response.text().await?); for title in &values.unwrap().applist.apps { println!("#{:?}: {}", title.appid, title.name); } Ok(()) }
普段phpしか触っていない人間にとっては、なかなか難しいけれど、学ぶ価値はあると思うので、地道にrustの学習進めていきたいと思う。