以前に ASP.NET Core WebAPI を Swashbuckle でドキュメント作って AutoRest でクライアントを生成してみました。
最近試したら違ったことになったのでアップデート記事です。
AutoRest 関連のアップデート記事はこちら
■ WebAPI を作る
最初はまずドキュメントを作る WebAPI を作ります。.NET Core がインストールされていればコンソールで一行です。
dotnet new webapi
かんたんですね。
■ Swashbuckle.AspNetCore をインストール
Swashbuckle.AspNetCore を NuGet からインストールします。 インストールとコードの追加は次のリンク先をなぞるだけです。
以前に試したときはビルドエラーが出てしまいプレリリース版の 5.0.0-rc5 をインストールし事なきを得ましたが、今回は普通に 5.0.0 のインストールで行けました。
■ アプリを起動し swagger.json をダウンロード
アプリを起動(デバッグ実行)します。Visual Studio で起動すると次の URL でブラウザが上がって来ると思います。
http://localhost:5000/weatherforecast
https://localhost:5001/weatherforecast
これを末尾を /swagger と打ち替え次のようなアドレスへ移動します。
http://localhost:5000/swagger
https://localhost:5001/swagger
すると API 仕様が記載されたページが出てきます。出てきたページの 「/swagger/v1/swagger.json」 リンクから swagger.json ファイルをダウンロードします。
ダウンロードした swagger.json は以前の時とは違い次のようになっていました。
{ "openapi": "3.0.1", "info": { "title": "My API", "version": "v1" }, "paths": { "/WeatherForecast": { "get": { "tags": [ "WeatherForecast" ], "responses": { "200": { "description": "Success", "content": { "text/plain": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/WeatherForecast" } } }, "application/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/WeatherForecast" } } }, "text/json": { "schema": { "type": "array", "items": { "$ref": "#/components/schemas/WeatherForecast" } } } } } } } } }, "components": { "schemas": { "WeatherForecast": { "type": "object", "properties": { "date": { "type": "string", "format": "date-time" }, "temperatureC": { "type": "integer", "format": "int32" }, "temperatureF": { "type": "integer", "format": "int32", "readOnly": true }, "summary": { "type": "string", "nullable": true } }, "additionalProperties": false } } } }
以前にはなかったらしい "additionalProperties": false
というプロパティがあります。
このプロパティが、AutoRest でクライアントコードを生成する際の新たなエラーになりました。
FATAL: Error parsing swagger file. Error converting value False to type 'AutoRest.Modeler.Model.Schema'. Path 'components.schemas.WeatherForecast.additionalProperties', line 1, position 2790. FATAL: AutoRest.Core.Logging.CodeGenerationException: Error parsing swagger file. Error converting value False to type 'AutoRest.Modeler.Model.Schema'. Path 'components.schemas.WeatherForecast.additionalProperties', line 1, position 2790.
■ 今回撮った対策
単純に additionalProperties
を削除しました。
■ これまで通りのエラー
これまで通りの次のエラーも出ます。
FATAL: OperationId is required for all operations. Please add it for 'get' operation of '/WeatherForecast' path.
これは先日の記事の通り、OperationId の追加で行けました。
■ かんたんですね
あとはすんなり先日の記事通りです。
かんたんですね。