Skip to content

Instantly share code, notes, and snippets.

@ScreamingHawk
Created April 4, 2017 19:46
Show Gist options
  • Save ScreamingHawk/2d239e0720c660c62061a28b69ecf467 to your computer and use it in GitHub Desktop.
Save ScreamingHawk/2d239e0720c660c62061a28b69ecf467 to your computer and use it in GitHub Desktop.
Convert a JSON file to a Swagger Definition
import sys
import json
def eexit(message):
"""Print a message and exit."""
print(message)
exit(1)
def convert(inFile, outFile):
"""Convert the JSON file to swagger YAML."""
data = None
with open(inFile, 'r') as fin:
data = json.loads(fin.read())
if not data:
eexit("Could not import JSON.")
with open(outFile, 'w') as fout:
outDict(data, fout, 0)
def outDict(obj, fout, indent):
"""Convert the dictionary at the given indentation level."""
for k in sorted(obj):
fout.write(' '*indent+k+':\n')
outType(obj[k], fout, indent+1)
def outType(v, fout, indent):
"""Convert the object at the given indentation level."""
if type(v) is dict:
fout.write(' '*indent+'type: object\n')
fout.write(' '*indent+'properties:\n')
outDict(v, fout, indent+1)
elif type(v) is float:
fout.write(' '*indent+'type: number\n')
fout.write(' '*indent+'format: double\n')
elif type(v) is int:
fout.write(' '*indent+'type: number\n')
fout.write(' '*indent+'format: int32\n')
elif type(v) is unicode:
fout.write(' '*indent+'type: string\n')
elif type(v) is list:
fout.write(' '*indent+'type: array\n')
fout.write(' '*indent+'items:\n')
if len(v) > 0:
outType(v[0], fout, indent+1)
else:
outType(None, fout, indent+1)
elif type(v) is bool:
fout.write(' '*indent+'type: boolean\n')
elif v is None:
fout.write(' '*indent+'type: object\n')
else:
eexit('No handling for: '+str(type(v)))
if __name__ == "__main__":
if len(sys.argv) <= 1:
eexit("Input file required.")
elif len(sys.argv) <= 2:
eexit("Output file requried.")
convert(sys.argv[1], sys.argv[2])
@ScreamingHawk
Copy link
Author

It's common for me to be asked to create a swagger document for an API after the API has been written. Sometimes the responses can be large and typing the definition by hand is consuming.

This script will take a JSON file and convert it to a swagger definition.

It does not add descriptions. It does not add endpoint information. It does not do anything fancy except create the definition for you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment