クライアントライブラリー生成#

APIリファレンス からダウンロードできるOpenAPI Specification形式のファイルをもとに、クライアントライブラリーを生成することができます。

ここでは例として、openapi-generator-cliを使ってクライアントを生成します。

openapi-generator-cliは、 npm を使って以下のコマンドでインストールします。

$ npm install @openapitools/openapi-generator-cli

重要

REST APIライブラリーのビルドおよび動作は、使用するコードジェネレーターの対応状況に依存します。 ジェネレーターが特定の機能をサポートしていない場合、ビルドエラーや予期しない動作が発生する可能性があります。 その場合は、ジェネレーターの仕様に応じた適切な対応が必要です。 対応方法としては、ジェネレーターの設定オプションを調整する、生成されたコードを修正するなどの方法があります。 本章では、ジェネレーターを使用したコードの生成手順について説明しますが、生成されたコードの修正については、各ジェネレーターの公式ドキュメントを参照してください。

重要

openapi-generator-cliは、Javaプログラム OpenAPI Generator を実行します。 そのため、以下の手順を行うには、Java実行環境がインストールされ、環境変数 PATH に java コマンドへのパスが含まれている必要があります。

各言語のクライアントライブラリーの生成は以下の手順で行います。

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

$ ./node_modules/.bin/openapi-generator-cli generate \
   -g go -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \
   -o <出力先: ./intdash>  \
   --package-name=<package名: intdash> \
   --git-host <生成するGitリポジトリのホスト名。例: git.example.co.jp> \
   --git-repo-id <生成するGitリポジトリのリポジトリ名。例: my-custom-application> \
   --git-user-id <生成するGitリポジトリの組織やユーザ名。例: company> \
   --additional-properties=disallowAdditionalPropertiesIfNotPresent=true,enumClassPrefix=true \
   --http-user-agent=<ユーザーエージェント>

使用するプロジェクトの go.mod ファイルに replace を追加します。

$ go mod edit -replace <Gitリポジトリのパス: git.example.co.jp/company/my-custom-application>=<出力先: ./intdash>

一部のAPIのエンコーディング方式にProtocol Bufferを使用できるように置換します。

$ sed -i -e "s/\"application\\/vnd.iscp.v2.protobuf\", \"application\\/json\"/\"application\\/vnd.iscp.v2.protobuf\"/g" ./intdash/*.go
$ sed -i -e "s/\"application\\/json; charset=utf-8\", \"application\\/protobuf\"/\"application\\/protobuf\"/g" ./intdash/*.go

コードのフォーマットを整えます。

$ gofmt -w ./
$ go mod tidy

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

$ ./node_modules/.bin/openapi-generator-cli generate \
  -g python -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \
  --package-name=apiclient

重要

上記openapi-generator-cliコマンドを実行すると、openapi-generatorが実行されます。 なお、この手順は、openapi-generator 6.1.0を使って動作確認済みです(2022年10月17日時点の最新版openapi-generator 6.2.0では正しく動作しません)。

使用するopenapi-generatorを6.1.0に切り替えるには、./node_modules/.bin/openapi-generator-cli version-manager set 6.1.0 を実行してください。

自動生成されたコードは次のライブラリーに依存します。

urllib3 = "^1.26.12"
python-dateutil = "^2.8.2"

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

$ ./node_modules/.bin/openapi-generator-cli generate \
-g rust -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \
-o ./intdash --package-name=intdash

重要

上記openapi-generator-cliコマンドを実行すると、openapi-generatorが実行されます。 なお、この手順は、openapi-generator 7.12.0を使って動作確認済みです。

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

$ git -C ./intdash apply << 'EOF'
diff --git a/src/apis/deprecated_apis_api.rs b/src/apis/deprecated_apis_api.rs
index e902156..35c7931 100644
--- a/src/apis/deprecated_apis_api.rs
+++ b/src/apis/deprecated_apis_api.rs
@@ -1071,7 +1071,12 @@ pub async fn create_data_points(configuration: &configuration::Configuration, bo
   if let Some(ref token) = configuration.bearer_access_token {
         req_builder = req_builder.bearer_auth(token.to_owned());
   };
-    req_builder = req_builder.body(p_body);
+    req_builder = if let Some(ref path) = p_body {
+        let file_content = std::fs::read(path)?;
+        req_builder.body(file_content)
+    } else {
+        req_builder.body(Vec::new())
+    };

   let req = req_builder.build()?;
   let resp = configuration.client.execute(req).await?;
@@ -1307,7 +1312,12 @@ pub async fn create_measurement_sequence_chunks(configuration: &configuration::C
   if let Some(ref token) = configuration.bearer_access_token {
         req_builder = req_builder.bearer_auth(token.to_owned());
   };
-    req_builder = req_builder.body(p_body);
+    req_builder = if let Some(ref path) = p_body {
+        let file_content = std::fs::read(path)?;
+        req_builder.body(file_content)
+    } else {
+        req_builder.body(Vec::new())
+    };

   let req = req_builder.build()?;
   let resp = configuration.client.execute(req).await?;
@@ -1457,7 +1467,12 @@ pub async fn create_project_data_points(configuration: &configuration::Configura
   if let Some(ref token) = configuration.bearer_access_token {
         req_builder = req_builder.bearer_auth(token.to_owned());
   };
-    req_builder = req_builder.body(p_body);
+    req_builder = if let Some(ref path) = p_body {
+        let file_content = std::fs::read(path)?;
+        req_builder.body(file_content)
+    } else {
+        req_builder.body(Vec::new())
+    };

   let req = req_builder.build()?;
   let resp = configuration.client.execute(req).await?;
diff --git a/src/apis/measurement_service_measurement_sequences_api.rs b/src/apis/measurement_service_measurement_sequences_api.rs
index c325392..bc45347 100644
--- a/src/apis/measurement_service_measurement_sequences_api.rs
+++ b/src/apis/measurement_service_measurement_sequences_api.rs
@@ -74,7 +74,12 @@ pub async fn create_project_measurement_sequence_chunks(configuration: &configur
   if let Some(ref token) = configuration.bearer_access_token {
         req_builder = req_builder.bearer_auth(token.to_owned());
   };
-    req_builder = req_builder.body(p_body);
+    req_builder = if let Some(ref path) = p_body {
+        let file_content = std::fs::read(path)?;
+        req_builder.body(file_content)
+    } else {
+        req_builder.body(Vec::new())
+    };

   let req = req_builder.build()?;
   let resp = configuration.client.execute(req).await?;
diff --git a/src/apis/measurement_service_uploading_measurements_api.rs b/src/apis/measurement_service_uploading_measurements_api.rs
index 5b79cd7..fa5176c 100644
--- a/src/apis/measurement_service_uploading_measurements_api.rs
+++ b/src/apis/measurement_service_uploading_measurements_api.rs
@@ -24,7 +24,7 @@ pub enum FileUploadProjectMeasurementError {


/// CSVファイルまたはMP4ファイル(MP4ファイルは実験的な機能です)をアップロードし、計測を作成します。 計測には、指定されたエッジUUIDが関連付けられます。  `base_time` (基準時刻)は、RFC3339による表現か、UNIX時刻(マイクロ秒)を指定してください。 基準時刻が指定されていない場合は、CSVファイルのデータ行の1行目の時刻が基準時刻として使用されます。 CSVファイルのデータは、時刻順にソートされている必要があります。 `meas_end` パラメーターの設定は任意です。指定しない場合、 `true` となります。  CSVファイルの例: ``` time,       col1,   col2, col3,      col4,   col5, col6,      col7,   col8, col9,      col10 1539263579, val11,  12,   13.12345,  val14,  15,   16.12345,  val17,  18, 19.12345,  val110 1539263580, val21,  22,   23.12345,  val24,  25,   26.12345,  val27,  28, 29.12345,  val210 1539263581, val31,  32,   33.12345,  val34,  35,   36.12345,  val37,  38, 39.12345,  val310 1539263582, val41,  42,   43.12345,  val44,  45,   46.12345,  val47,  48, 49.12345,  val410 ``` 空白行がある場合、行番号のカウントは加算されますが、その行は処理されません。 例えば、以下のような場合の空白行は無視されます。 ``` time,       col1,   col2, col3,      col4,   col5, col6,      col7,   col8, col9,      col10 1539263579, val11,  12,   13.12345,  val14,  15,   16.12345,  val17,  18, 19.12345,  val110  1539263581, val31,  32,   33.12345,  val34,  35,   36.12345,  val37,  38, 39.12345,  val310 1539263582, val41,  42,   43.12345,  val44,  45,   46.12345,  val47,  48, 49.12345,  val410 ```  [Go parser library](https://golang.org/pkg/encoding/csv/) も参照してください。  時刻の列には、RFC3339による表現か、UNIX時刻(秒)を使用することができます。 ## エスケープ 値の内部で `,` を使用したい場合は、その値全体を `\"` で囲んでください。 また、値の内部で `\"` を使用したい場合は、値全体を `\"` で囲み、さらに、 `\"` を `\"\"` のように表記してください。 値を `\"` で囲まないと、CSVファイルのパースの際にエラーが発生します。  エスケープの例: ``` time,col1 1539263579,\"ab,cde\"                  .....OK (parsed as 'ab,cde') 1539263579,\"ab\"\"cde\"                 .....OK (parsed as 'ab\"cde') 1539263579,     abcde                .....OK (parsed as '     abcde') 1539263579,\"     abcde\"              .....OK (parsed as '     abcde') 1539263579,ab\"cde                    .....NG 1539263579, \"abcde\"                  .....NG 1539263579,ab,cde                    .....NG(wrong number of fields) ```
-pub async fn file_upload_project_measurement(configuration: &configuration::Configuration, project_uuid: &str, edge_uuid: &str, data_file: std::path::PathBuf, base_time: Option<String>, base_time_name: Option<models::String>, base_time_priority: Option<models::i32>, meas_end: Option<bool>, label_data_type: Option<&str>) -> Result<models::MeasurementFileUploadPostResponse, Error<FileUploadProjectMeasurementError>> {
+pub async fn file_upload_project_measurement(configuration: &configuration::Configuration, project_uuid: &str, edge_uuid: &str, data_file: std::path::PathBuf, base_time: Option<String>, base_time_name: Option<String>, base_time_priority: Option<i32>, meas_end: Option<bool>, label_data_type: Option<&str>) -> Result<models::MeasurementFileUploadPostResponse, Error<FileUploadProjectMeasurementError>> {
   // add a prefix to parameters to efficiently prevent name collisions
   let p_project_uuid = project_uuid;
   let p_edge_uuid = edge_uuid;

EOF

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

$ ./node_modules/.bin/openapi-generator-cli generate \
-g typescript-axios -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \
-o ./intdash \
--additional-properties=useSingleRequestParameter=true

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

$ ./node_modules/.bin/openapi-generator-cli generate \
-g swift5 -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml \
-o ./intdash \
--additional-properties=hashableModels=false,projectName=intdash,removeMigrationProjectNameClass=true

重要

上記openapi-generator-cliコマンドを実行すると、openapi-generatorが実行されます。 なお、この手順は、openapi-generator 6.0.0を使って動作確認済みです(2022年10月17日時点の最新版openapi-generator 6.2.0では正しく動作しません)。

使用するopenapi-generatorを6.0.0に切り替えるには、./node_modules/.bin/openapi-generator-cli version-manager set 6.0.0 を実行してください。

CocoaPodsで利用できるバージョン表記は X.Y.Z 形式のみのため、生成されたコードの .podspec を修正します。

s.version = 'v2.4.0'
↓
s.version = '2.4.0'

Podfile で以下のように設定します。

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target '{YOUR_APP_NAME}' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for {YOUR_APP_NAME}
  pod 'intdash', :path => '../intdash/'

end

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

openapi-generator-cli generate -i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml -g csharp-netcore --library httpclient -o intdash --additional-properties=netCoreProjectFile=true,targetFramework=netstandard2.0,packageName=intdash,validatable=false,supportsRetry=false

Unityで使用する場合、以下の手順でUnityプロジェクト内にセットアップします。

  1. 先ほど生成したintdashクライアントライブラリー内の src/intdash ディレクトリを、Unityプロジェクト {YOUR_UNITY_PROJECT}/Assets/Plugins/ にコピーします。

  2. Unityにデフォルトで入っているNewtonsoft.Jsonを削除します。

    • プロジェクトのPackagesに Newtonsoft.Json が存在する場合は Newtonsoft.Json を削除します。

    • Version Control で使用されている Newtonsoft.Json は、PackageManagerより Version Control を削除することで削除できます。

  3. 依存ライブラリーをダウンロードします。

    intdashクライアントライブラリーは以下のライブラリーに依存しています。

    • JsonSubTypes

    • Newtonsoft

    NuGet CLI を使って、以下のコマンドで依存ライブラリーをダウンロードします。

    nuget install JsonSubTypes -DisableParallelProcessing -Framework netstandard2.0 -OutputDirectory ./packages
    

    その後、ダウンロードしたDLLファイルを {YOUR_UNITY_PROJECT}/Assets/Plugins/intdash/ 配下にコピーします。

    • ./packages/JsonSubTypes.{VERSION}/lib/netstandard2.0/JsonSubTypes.dll

      → {YOUR_UNITY_PROJECT}/Assets/Plugins/intdash/JsonSubTypes.dll

    • ./packages/Newtonsoft.Json.{VERSION}/lib/netstandard2.0/Newtonsoft.Json.dll

      → {YOUR_UNITY_PROJECT}/Assets/Plugins/intdash/Newtonsoft.Json.dll

  4. intdashクライアント用のメタデータを作成します。

    {YOUR_UNITY_PROJECT}/Assets/Plugins/intdash/ 配下に以下の2つのファイルを作成してください。

    • intdash.asmdef (※intdashフォルダ配下をアセンブリ化します)

      {
        "name": "intdash"
      }
      
    • link.xml (※IL2CPPによるビルド時のエラー回避用)

      <linker>
          <assembly fullname="System.Core">
                <type fullname="System.Linq.Expressions.Interpreter.LightLambda" preserve="all" />
          </assembly>
      </linker>
      

プロジェクトルートにて以下のコマンドを実行します。 -i オプションでOpenAPI Specificationファイルを指定してください。 ${VERSION} では v2.4.0 のようなバージョン名を指定してください。

(ここではJavaでクライアントライブラリーを生成していますが、生成されたライブラリーはKotlinと互換性があります。)

$ ./node_modules/.bin/openapi-generator-cli generate \
-i https://docs.intdash.jp/api/intdash-api/${VERSION}/openapi_public.yaml -g java -o intdash \
--additional-properties=library=okhttp-gson,apiPackage=com.aptpod.intdash,groupId=com.aptpod,artifactId=intdash,sourceFolder=src/main/java,disallowAdditionalPropertiesIfNotPresent=false

重要

上記openapi-generator-cliコマンドを実行すると、openapi-generatorが実行されます。 なお、この手順は、openapi-generator 6.6.0を使って動作確認済みです。

使用するopenapi-generatorを6.6.0に切り替えるには、./node_modules/.bin/openapi-generator-cli version-manager set 6.6.0 を実行してください。

生成されたクライアントのAndroidへのセットアップ:

  1. ビルドエラーを回避するために一部のコードを修正します。

    自動生成されたコードはそのままではビルドできないため、一部を修正する必要があります。 パッチを適用して修正する例を以下に示します。

    diff --git a/intdash/src/main/java/org/openapitools/client/model/DataPointTime.java b/intdash/src/main/java/org/openapitools/client/model/DataPointTime.java
    index e358477..5b03290 100644
    --- a/intdash/src/main/java/org/openapitools/client/model/DataPointTime.java
    +++ b/intdash/src/main/java/org/openapitools/client/model/DataPointTime.java
    @@ -101,7 +101,7 @@ public class DataPointTime extends AbstractOpenApiSchema {
                         // deserialize Long
                         try {
                             // validate the JSON object to see if any exception is thrown
    -                        Long.validateJsonObject(jsonObject);
    +                        //Long.validateJsonObject(jsonObject);
                             actualAdapter = adapterLong;
                             match++;
                             log.log(Level.FINER, "Input data matches schema 'Long'");
    @@ -114,7 +114,7 @@ public class DataPointTime extends AbstractOpenApiSchema {
                         // deserialize String
                         try {
                             // validate the JSON object to see if any exception is thrown
    -                        String.validateJsonObject(jsonObject);
    +                        //String.validateJsonObject(jsonObject);
                             actualAdapter = adapterString;
                             match++;
                             log.log(Level.FINER, "Input data matches schema 'String'");
    @@ -234,7 +234,7 @@ public class DataPointTime extends AbstractOpenApiSchema {
         ArrayList<String> errorMessages = new ArrayList<>();
         // validate the json string with Long
         try {
    -      Long.validateJsonObject(jsonObj);
    +      //Long.validateJsonObject(jsonObj);
           validCount++;
         } catch (Exception e) {
           errorMessages.add(String.format("Deserialization for Long failed with `%s`.", e.getMessage()));
    @@ -242,7 +242,7 @@ public class DataPointTime extends AbstractOpenApiSchema {
         }
         // validate the json string with String
         try {
    -      String.validateJsonObject(jsonObj);
    +      //String.validateJsonObject(jsonObj);
           validCount++;
         } catch (Exception e) {
           errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage()));
    
  2. .jarパッケージを生成します。

    パッケージの生成には Maven を使用します。

    $ cd intdash
    $ mvn clean package
    
  3. 生成されたパッケージをAndroidプロジェクトにコピーします。

    • 生成されたパッケージのパス: intdash/target/intdash-***.jar

    • コピー先: {YOUR_ANDROID_PROJECT}/{YOUR_APPLICATION_FOLDER}/libs

  4. 一部の依存ライブラリーもAndroidプロジェクトにコピーします。

    • 依存ライブラリーのパス: intdash/target/lib/javax.ws.rs-api-2.1.1.jar

    • コピー先: {YOUR_ANDROID_PROJECT}/{YOUR_APPLICATION_FOLDER}/libs

  5. build.gradle に依存関係を追記します。

    ...
    dependencies {
        implementation fileTree(dir: 'libs', include: ['*.jar', '*.aar'])
        ...
        // Dependencies for intdash API
        implementation 'com.squareup.okhttp3:okhttp:4.10.0'
        implementation 'com.google.code.gson:gson:2.9.1'
        implementation 'io.gsonfire:gson-fire:1.8.5'
    }