Rust

OpenAPI Specificationから生成 されたRust用クライアントライブラリを使用するサンプルを示します。

Cargo.tomlに以下のライブラリへの依存が定義されていることを前提としています。

[dependencies]
tokio = { version = "1.21", features = ["rt", "macros"] }
oauth2 = { version = "4.2" }
intdash = { path = "./intdash" }

APIトークンを使用してAPIにアクセスする

以下のコードでは、APIトークンを使用して認証を行います。その後、認証したユーザー自身の情報を取得します。

実行時には以下を指定してください。

  • url: 接続先intdash APIのベースURL

  • api_token: ユーザーのAPIトークン(APIトークンはMy Pageで作成できます)

use intdash::apis::{
    auth_edges_api::get_me_as_edge,
    configuration::{ApiKey, Configuration},
};

#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "http://localhost:8080/api";
    let api_token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    let mut cfg = Configuration::new();
    cfg.base_path = url.to_string();
    cfg.api_key = Some(ApiKey {
        prefix: None,
        key: api_token.to_string(),
    });

    let me = get_me_as_edge(&cfg).await?;

    println!("Hello {}", me.name);

    Ok(())
}

OAuth2トークンを使用してAPIにアクセスする

以下のコードでは、OAuth2トークンを使って認証を行います。その後、認証したユーザー自身の情報を取得します。

実行時には以下を指定してください。

  • url: 接続先intdash APIのベースURL

  • client_id: エッジのUUID

  • client_secret: エッジの作成時に発行されるクライアントシークレット

use oauth2::{
    basic::BasicClient, reqwest::async_http_client, AuthType, AuthUrl, ClientId, ClientSecret,
    TokenResponse, TokenUrl,
};

use intdash::apis::{auth_edges_api::get_me_as_edge, configuration::Configuration};

#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "http://localhost:8080/api";
    let client_id = "00000000-0000-0000-0000-000000000000";
    let client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    let c = BasicClient::new(
        ClientId::new(client_id.to_string()),
        Some(ClientSecret::new(client_secret.to_string())),
        AuthUrl::new(format!("{}{}", url, "/auth/oauth2/authorization"))?,
        Some(TokenUrl::new(format!("{}{}", url, "/auth/oauth2/token"))?),
    )
    .set_auth_type(AuthType::RequestBody);

    let token_result = c
        .exchange_client_credentials()
        .request_async(async_http_client)
        .await?;

    let mut cfg = Configuration::new();
    cfg.base_path = url.to_string();
    cfg.bearer_access_token = Some(token_result.access_token().secret().to_string());

    let me = get_me_as_edge(&cfg).await?;

    println!("Hello {}", me.name);

    Ok(())
}

過去の計測のデータポイントを取得する

データポイントを取得する場合、自動生成されたコードはそのままでは使用できず、一部を修正する必要があります。 パッチを適用して修正する例を以下に示します(ヒアドキュメントを使用しているため全ての行で1つのコマンドです)。

$ git -C ./intdash apply << 'EOF'
diff --git a/src/apis/meas_data_points_api.rs b/src/apis/meas_data_points_api.rs
index 32d5de8..6fa0dc6 100644
--- a/src/apis/meas_data_points_api.rs
+++ b/src/apis/meas_data_points_api.rs
@@ -403,7 +403,7 @@ pub async fn list_project_data_ids_with_measurement_uuid(configuration: &configu
 }

 /// データポイントのリストを取得します。 返却されるデータポイントはJSON形式です。データポイントごとに改行で区切られます。
-pub async fn list_project_data_points(configuration: &configuration::Configuration, project_uuid: &str, name: &str, idq: Option<Vec<String>>, start: Option<&str>, end: Option<&str>, since: Option<&str>, exit_on_error: Option<&str>, label: Option<Vec<String>>, period: Option<i64>, limit: Option<i32>, order: Option<&str>, time_format: Option<&str>) -> Result<std::path::PathBuf, Error<ListProjectDataPointsError>> {
+pub async fn list_project_data_points(configuration: &configuration::Configuration, project_uuid: &str, name: &str, idq: Option<Vec<String>>, start: Option<&str>, end: Option<&str>, since: Option<&str>, exit_on_error: Option<&str>, label: Option<Vec<String>>, period: Option<i64>, limit: Option<i32>, order: Option<&str>, time_format: Option<&str>) -> Result<Vec<serde_json::Value>, Error<ListProjectDataPointsError>> {
     let local_var_configuration = configuration;

     let local_var_client = &local_var_configuration.client;
@@ -470,7 +470,12 @@ pub async fn list_project_data_points(configuration: &configuration::Configurati
     let local_var_content = local_var_resp.text().await?;

     if !local_var_status.is_client_error() && !local_var_status.is_server_error() {
-        serde_json::from_str(&local_var_content).map_err(Error::from)
+        let mut data_points: Vec<serde_json::Value> = Vec::new();
+        for line in local_var_content.lines() {
+            let d = serde_json::from_str(line).map_err(Error::from)?;
+            data_points.push(d);
+        }
+        Ok(data_points)
     } else {
         let local_var_entity: Option<ListProjectDataPointsError> = serde_json::from_str(&local_var_content).ok();
         let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
EOF

そのうえで、以下のようにデータポイントを取得します。

  • url: 接続先intdash APIのベースURL

  • client_id: エッジのUUID

  • client_secret: エッジの作成時に発行されるクライアントシークレット

  • measurement_uuid: 計測のUUID

use oauth2::{
    basic::BasicClient, reqwest::async_http_client, AuthType, AuthUrl, ClientId, ClientSecret,
    TokenResponse, TokenUrl,
};

use intdash::apis::{configuration::Configuration, meas_data_points_api::list_project_data_points};

#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let url = "http://localhost:8080/api";
    let client_id = "00000000-0000-0000-0000-000000000000";
    let client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    let measurement_uuid = "00000000-0000-0000-0000-000000000000";

    let c = BasicClient::new(
        ClientId::new(client_id.to_string()),
        Some(ClientSecret::new(client_secret.to_string())),
        AuthUrl::new(format!("{}{}", url, "/auth/oauth2/authorization"))?,
        Some(TokenUrl::new(format!("{}{}", url, "/auth/oauth2/token"))?),
    )
    .set_auth_type(AuthType::RequestBody);

    let token_result = c
        .exchange_client_credentials()
        .request_async(async_http_client)
        .await?;

    let mut cfg = Configuration::new();
    cfg.base_path = url.to_string();
    cfg.bearer_access_token = Some(token_result.access_token().secret().to_string());

    let data_points = list_project_data_points(
        &cfg,
        "00000000-0000-0000-0000-000000000000",
        measurement_uuid,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        None,
        Some("ns"),
    )
    .await?;

    println!("Data Points {:?}", data_points);

    Ok(())
}