Skip to content

Instantly share code, notes, and snippets.

@pocc
Created January 25, 2019 23:54
Show Gist options
  • Save pocc/b0e1f84e165c7b13a12a3c8e53a6c9ed to your computer and use it in GitHub Desktop.
Save pocc/b0e1f84e165c7b13a12a3c8e53a6c9ed to your computer and use it in GitHub Desktop.
Automatically generate a Python Meraki API module from the Mearki API website
# -*- coding: utf-8 -*-
"""Generator for Meraki API python module"""
import requests
import json
import re
api_key = ''
base_url = 'https://api.meraki.com/api/v0/'
# Should work for get
function_text = """\ndef {0}({1}):
\tresponse = requests.{2}('{3}{4}',{5} headers=headers)
\treturn response\n"""
headers = {
'X-Cisco-Meraki-API-Key': api_key,
'Content-Type': 'application/json',
}
def get_json_from_pagetext(page_text):
"""Get the API JSON from the API page text by splitting it twice."""
lower_split = page_text.split("window.allApisJson = ")[1]
all_api_docs_str = lower_split.split(";\n </script>")[0]
return json.loads(all_api_docs_str)
def make_snake_case(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
# Idea is to have a class per Meraki section.
generated_text = """class MerakiApi:
\"\"\"Python class to access the Meraki API \
(https://create.meraki.io/guides/dashboard-api/)\"\"\"
def __init__(self, api_key):
self.api_key = api_key
"""
meraki_apidocs = 'https://dashboard.meraki.com/api_docs'
pagetext = requests.get(meraki_apidocs).text
all_apis_json = get_json_from_pagetext(pagetext)
api_calls = {}
for category in all_apis_json:
for api_call in all_apis_json[category]:
print(api_call)
http_type = api_call['http_method']
full_path_name_with_empties = api_call['path'].split('/')
# Sometimes an API call will end with '/'.
full_path_name = list(filter(None, full_path_name_with_empties))
if full_path_name[-1][0] == '[':
# For /organizations/[organization_id]/admins/[id]
# we get put_admins_by_id
path_name = full_path_name[-2] + '_by_' + full_path_name[-1][1:-1]
else:
path_name = full_path_name[-1]
api_call_name = http_type.lower() + '_' + make_snake_case(path_name)
api_calls[api_call_name] = api_call['description']
if api_call['http_method'] == 'GET':
data = ''
else:
data = ''
generated_text += function_text.format(
api_call_name,
'~',
api_call['http_method'].lower(),
api_key,
base_url,
data)
print(generated_text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment