はじめに
ビジネス統括本部のイチノです。最近は、ChatGPTにシェルスクリプトの書き方を教えてもらっています。
今回は、OpenAPIのschemasで JSONデータを検証する方法のメモです。
検証方法
openapi-schema-validator というライブラリを利用して JSON データがOpenAPIの schemas に合致するかを検証します。
サンプルは以下のとおりです。説明用に OpenAPI のドキュメントや JSON データを直接書いています。利用する際は、データの直書きではなくファイル読み込みに修正すると使い勝手が良くなります。
#!/usr/bin/env python3 import json import yaml from openapi_schema_validator import validate from jsonschema.validators import RefResolver OPENAPI_SPEC = ''' openapi: 3.0.3 info: title: OpenAPI ドキュメント version: 1.0.0 paths: # 省略 components: schemas: Server: type: object properties: os: type: string admin: $ref: '#/components/schemas/User' User: type: object properties: id: type: integer name: type: string password: type: string ''' TEST_JSON = ''' { "os": "Linux", "admin": { "id": 1000, "name": "optim", "password": "1234567890" } } ''' def main(): spec = yaml.safe_load(OPENAPI_SPEC) schemas = spec['components']['schemas'] ref_resolver = RefResolver.from_schema(spec) example = json.loads(TEST_JSON) validate(example, schemas['Server'], resolver=ref_resolver) print('Succeeded!') if __name__ == '__main__': main()
実行に必要なライブラリを pip でインストール。
$ pip install openapi-schema-validator pyyaml
実行して検証に成功すると Succeeded!
と出力されます。
$ python3 test.py
Succeeded!
試しにJSON_DATAの "os" を 1
に書き換えると、不正なJSONデータとして検知してくれます。
Traceback (most recent call last): File "/app/test.py", line 58, in <module> main() File "/app/test.py", line 54, in main validate(example, schemas['Server'], resolver=ref_resolver) File "/usr/local/lib/python3.11/site-packages/openapi_schema_validator/shortcuts.py", line 23, in validate raise error jsonschema.exceptions.ValidationError: 1 is not of type 'string' Failed validating 'type' in schema['properties']['os']: {'type': 'string'} On instance['os']: 1
おわりに
OpenAPI のschemas でJSONデータを検証する方法を紹介しました。エンジニアに限らず募集中ですので、ぜひご覧ください!