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

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

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

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

$ npm install @openapitools/openapi-generator-cli

重要

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-custome-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 ./
$ gomod 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

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

$ git -C ./intdash apply << 'EOF'
diff --git a/src/models/data_point_data_error.rs b/src/models/data_point_data_error.rs
index 93cff1e..79171ef 100644
--- a/src/models/data_point_data_error.rs
+++ b/src/models/data_point_data_error.rs
@@ -12,7 +12,7 @@



-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
 pub struct DataPointDataError {
     /// 固定値 `intdash/measurement/get/data/error`
     #[serde(rename = "i")]
diff --git a/src/models/data_point_error.rs b/src/models/data_point_error.rs
index 33248c6..182ed04 100644
--- a/src/models/data_point_error.rs
+++ b/src/models/data_point_error.rs
@@ -11,7 +11,7 @@



-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
 pub struct DataPointError {
     #[serde(rename = "time")]
     pub time: Box<crate::models::DataPointTime>,
diff --git a/src/models/signal.rs b/src/models/signal.rs
index 70065f6..6988f45 100644
--- a/src/models/signal.rs
+++ b/src/models/signal.rs
@@ -11,7 +11,7 @@



-#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
 pub struct Signal {
     /// 信号定義のUUID
     #[serde(rename = "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'
    }