1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【OpenAPIGenerator】mustacheファイルで末尾カンマを除去するには、`{{^-last}},{{/-last}}`を使えばよい

Last updated at Posted at 2022-03-16

環境

  • 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の意味は見つけられなかったので、今回調べたことを記事にしました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?