Skip to content

Instantly share code, notes, and snippets.

@mermoldy
Last active August 9, 2016 16:14
Show Gist options
  • Save mermoldy/80284318e0ed2640828f367ca8ae79df to your computer and use it in GitHub Desktop.
Save mermoldy/80284318e0ed2640828f367ca8ae79df to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import yaml
import json
import click
import requests
API_VERSION = 'v1beta0'
DEFAULTS = {
'string': '',
'boolean': True,
'integer': 1,
'array': []
}
def load_user_spec():
resp = requests.get('https://my.scalr.net/api/user.{}.yml'
.format(API_VERSION))
resp_dict = yaml.load(resp.text)
if 'errorMessage' in resp_dict:
raise Exception(resp_dict['errorMessage'])
else:
return resp_dict
def item_by_ref(spec_data, ref):
_, _, definition = ref.strip('/').split('/')
return spec_data['definitions'][definition]
def get_params(spec_data, schema):
params = {}
if '$ref' in schema:
schema = item_by_ref(spec_data, schema['$ref'])
if 'properties' in schema:
for p_key, p_value in schema['properties'].items():
if '$ref' in p_value:
sub_item = item_by_ref(spec_data, p_value['$ref'])
params[p_key] = get_params(spec_data, sub_item)
else:
if 'enum' in p_value:
params[p_key] = p_value['enum'][0]
else:
params[p_key] = DEFAULTS[p_value['type']]
return params
def user_post_data(spec_data, endpoint):
"""Generate POST data for specified user API endpoint.
:param spec_data
:param endpoint: /api/vN/user/{envId}/'
:return: post_data
"""
base_path = spec_data['basePath']
if endpoint.startswith(base_path):
endpoint = endpoint.replace(base_path, '', 1)
else:
raise Exception('API\'s basePath: {} and endpoint does not match'
.format(base_path))
if endpoint in spec_data['paths']:
params_spec = spec_data['paths'].get(endpoint)
else:
raise Exception('API endpoint {} does not found'.format(endpoint))
if 'post' in params_spec:
if 'parameters' in params_spec['post']:
schema = params_spec['post']['parameters'][0]['schema']
post_data = get_params(spec_data, schema)
else:
post_data = {}
else:
raise Exception('POST method for endpoint {} does not exist'
.format(endpoint))
return post_data
if __name__ == '__main__':
spec_data = load_user_spec()
for endpoint, params_spec in spec_data['paths'].items():
if 'post' in params_spec:
params = user_post_data(spec_data,
spec_data['basePath'] + endpoint)
click.echo('path: {}'.format(endpoint))
click.echo('post: {}\n'.format(json.dumps(params, indent=2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment