
【Unity】OpenAPI(Swagger)からopenapi-generator-cliを使用してコードを自動生成する
Swaggerで定義したAPI仕様書から型や、API Request処理をUnity(C#)に自動生成する手順を備忘録として記載します。
環境
OS : Mac(M1) 14.3.1
Unity : 2022.3.9f1
Swagger準備
まず、サンプルとして下記のようにopenapi.yamlを作成します。
openapi: "3.0.3"
info:
  title: "Sample API"
  version: "1.0.0"
paths:
  /api/v1/hello-world:
    get:
      summary: "hello world"
      responses:
        200:
          description: "success"
          content:
            application/json:
              schema:
                type: string
                example: "hello world!"
コードを自動生成する
openapi-generator-cliが未インストールの方は、下記でインストールします。
npm install @openapitools/openapi-generator-cli -g
下記コマンドを実行し、生成コードをoutput_directoryに出力します。
openapi-generator-cli generate -i ./openapi.yaml -g csharp -o ./output_directory
生成コードの「src/Org.OpenAPITools」のみが欲しいので、一時ディレクトリに書き出した後に必要な部分のみを書き出しています。
cp -r ./output_dirctory/src/Org.OpenAPITools/ /path/to/unity-proj/Assets/Scripts/Generated
モックサーバを立ち上げる
今回はクライアント(Unity)側のAPIの自動生成をして、APIを呼び出すわけですが、そのために呼び出されるAPIが必要です。
実装しても問題ないですが、今回は、モックサーバを立ち上げ確認していきます。
docker-compose.yamlを作成し、下記の内容を記載します。
version: "3"
services:
  swagger-mock:
    image: stoplight/prism:3
    ports:
      - "4010:4010"
    command: mock -h 0.0.0.0 /openapi.yaml
    restart: on-failure
    volumes:
      - ./openapi.yaml:/openapi.yaml
docker-compose.yamlを作成したのと同階層で、下記コマンドを実行し、コンテナを立ち上げます。
docker compose up -d
立ち上がったのを確認したら、下記コマンドで「hello world!」が返ってくることを確認します。
curl --location 'http://localhost:4010/api/v1/hello-world'
生成コードからAPIを呼びだす
まずunityに必要なパッケージを追加します。
NuGet-importer-for-Unity を使用するために、manifest.jsonのdependenciesセクションに下記を追加します。
{
  "dependencies": {
    ...
    "org.kumas.nuget-importer": "https://github.com/kumaS-nu/NuGet-importer-for-Unity.git?path=NuGetImporterForUnity/Packages/NuGet Importer"
  }
}
正常に追加されると、HeaderメニューにNuGet Impoterという項目が追加されます。
この中の一番上、Manager Importerを開きます。

ここから、必要なパッケージを選択し、installします。

必要なパッケージは、先ほど、コード出力したフォルダ(output_directory)のREADME.mdに記載されています。
version等は、使用しているopenapi-generator-cliのversionに依存するので、自身の環境に合わせて用意します。
<a id="dependencies"></a>
## Dependencies
- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.13.0 or later
- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.2 or later
- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later
- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later
unity側にAPIを呼び出すためのコードを記述します。
(動作しない場合、README.mdにもexampleがあると思いますので、そちらを参考にしてください。)
void Start(){
    var host = "http://localhost:4010";
    var apiInstance = new Org.OpenAPITools.Api.DefaultApi(host);
    var res = apiInstance.ApiV1HelloWorldGet();
    Debug.Log(res);
}
Unityを再生し、「hello world!」が返却されたことを確認します。
 

