環境
- OpenAPI Generator v5.4.1
- Python 3.10.2
やりたいこと
OpenAPIGeneratorを使って、Pythonのクライアントライブラリを作りたいです。
petstore.yaml
openapi: "3.0.0"
info:
version: 1.0.0
title: Swagger Petstore
servers:
- url: http://petstore.swagger.io/v1
paths:
/foo/{foo_id}/bar/{bar_id}:
get:
operationId: getFooBar
parameters:
- name: foo_id
in: path
required: true
schema:
type: string
- name: bar_id
in: path
required: true
schema:
type: string
responses:
'200':
description: foo
content:
application/json:
schema:
type: string
たとえば、上記のOpenAPI Specificationファイルから、以下のメソッドを作りたいです。
def get_foo_bar(foo_id, bar_id):
pass
パスパラメータはメソッドの引数として受け取れるようにします。
実現方法
openapi-generator-cliコマンドに、以下のmustacheファイルをテンプレートとして渡せば、上記のメソッドが出力されます。
template/api.mustache
{{#operations}}
{{#operation}}
def {{operationId}}({{#pathParams}}{{paramName}}{{^-last}}, {{/-last}}{{/pathParams}}):
pass
{{/operation}}
{{/operations}}
{{^-last}}, {{/-last}}
は、「pathParam
が最後の要素でなければ、,
を出力する」ことを表します。
openapi-generator-cliコマンドを実行すると、「引数の末尾にカンマがない」メソッドが出力されました。
$ docker run --rm -u `id -u`:`id -g` -v ${PWD}:/local openapitools/openapi-generator-cli:v5.4.0 generate \
--input-spec /local/petstore.yaml --generator-name python --output /local/out --template-dir /local/template \
--global-property apis,apiTests=false,apiDocs=false
out/openapi_client/api/default_api.py
def get_foo_bar(foo_id,bar_id):
pass
補足
記事を書いたきっかけ
既存のテンプレートファイルを眺めていたとき、-last
の意味が分かりませんでした。
Google検索で-last
の意味は見つけられなかったので、今回調べたことを記事にしました。