Created
August 13, 2018 21:02
-
-
Save KyleJamesWalker/81a47dbcf70e601e229526e0214875ca to your computer and use it in GitHub Desktop.
Find Swagger/OpenApi Spec Examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import yaml | |
def iter_cases(root, obj=None, template=None): | |
"""Find and yield example responses in the spec | |
Since examples are free-form as mentioned in the following | |
https://swagger.io/docs/specification/adding-examples/ | |
This function assumes each example resonse is key by a unique name, | |
see the simple_api.yaml for an example spec. | |
""" | |
if obj is None: | |
obj = {} | |
# Seed template | |
template = template or [ | |
'{path}', | |
'{method}', | |
'responses', | |
'{status}', | |
'examples', | |
'{name}', | |
'{test_case}', | |
] | |
# Process top entry from template | |
item = template[0] | |
template = template[1::] | |
item_key = item.strip("{}") | |
iter_items = item != item_key | |
# Done processing | |
if not template: | |
obj[item_key] = root | |
yield obj | |
return | |
if iter_items: | |
for key, children in root.items(): | |
obj[item_key] = key | |
yield from iter_cases(children, obj.copy(), template) | |
elif item in root: | |
yield from iter_cases(root[item], obj, template) | |
def main(): | |
with open('simple_api.yaml', 'r') as spec_fp: | |
spec = yaml.load(spec_fp) | |
for values in iter_cases(spec['paths']): | |
print(values) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
definitions: | |
HealthCheck: | |
properties: | |
status: {type: string} | |
required: [status] | |
type: object | |
info: {title: Simple Service, version: v1} | |
parameters: {} | |
paths: | |
/healthcheck: | |
get: | |
description: Healthcheck endpoint to check status of app | |
operationId: healthcheck | |
parameters: [] | |
responses: | |
200: | |
description: '' | |
examples: | |
base: {status: healthy} | |
malformed: {foo: bar} | |
schema: {$ref: '#/definitions/HealthCheck'} | |
tags: [v1, Healthcheck]swagger: '2.0' | |
tags: | |
- {name: v1} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment