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.

OpenAPI 3.0 の使い方 (POST 引数付き)

Last updated at Posted at 2021-10-22

仕様を記述##

POST で http://localhost:8080/hello に引数を与えてアクセスするとリスポンスがある。

post_hello.yaml
openapi: 3.0.2
info:
  description: ユーザ名を与えると挨拶を返してくれるAPI
  version: 1.0.0
  title: POST Hello
tags:
  - name: post_hello
    description: ユーザに挨拶を返すAPI
paths:
  /hello:
    post:
      tags:
        - hello
      description: ユーザに挨拶する。
      parameters: []
      requestBody:
        description: user to create
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/User'
            example:
              id: 362
              name: Richard Roe
      responses:
        "200":
          description: Success
          content:
            application/json:
              schema:
                type: object
                properties:
                  HelloUser:
                    type: string
                    example: Hello, userName
        "400":
          description: Bad Request
        "500":
          description: Internal Server Error
components:
  schemas:
    User:
      type: object
      required:
        - id
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string

https://editor.swagger.io/ でバリデート
post_hello_aa.png

Flask のサーバーを作成##

Generate Server -> python-flask

python-flask-server-generated.zip が出来る

解凍

unzip python-flask-server-generated.zip

ライブラリーのインストール

pip3 install -r requirements.txt

コードの修正

swagger_server/controllers/hello_controller.py
省略
#    return 'do some magic!'
    return 'Hello! ' + str(body.id) + ' ' + body.name

サーバー実行

python3 -m swagger_server

クライアントでアクセス

$ http POST http://0.0.0.0:8080/hello < in01.json
HTTP/1.0 200 OK
Content-Length: 19
Content-Type: application/json
Date: Fri, 22 Oct 2021 08:15:44 GMT
Server: Werkzeug/1.0.1 Python/3.9.7

"Hello! 567 Scott"

in01.json
{
"id": 567,
"name": "Scott"
}
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?