Skip to content

Instantly share code, notes, and snippets.

@AdrianMachado
Created November 5, 2024 08:10
Show Gist options
  • Save AdrianMachado/c7678a5cedf2c3f0e899042c10acc91c to your computer and use it in GitHub Desktop.
Save AdrianMachado/c7678a5cedf2c3f0e899042c10acc91c to your computer and use it in GitHub Desktop.
Python Hug OpenAPI/Swagger Documentation Converter
import yaml
from collections import OrderedDict
def convert_to_openapi(hug_doc):
"""
Converts Hug documentation to OpenAPI format.
:param hug_doc: Documentation generated from Hug framework's annotations.
:return: A dictionary in OpenAPI 3.0 format.
"""
openapi = OrderedDict({
"openapi": "3.0.0",
"info": {
"title": "Hug API Documentation",
"version": str(hug_doc.get("version", "1.0.0")),
"description": hug_doc.get("overview", "API Documentation generated from Hug API"),
},
"servers": [
{"url": "{base_url}"}
],
"paths": OrderedDict(),
})
handlers = hug_doc.get("handlers", OrderedDict())
for path, methods in handlers.items():
path_item = OrderedDict()
for method, doc_data in methods.items():
operation = {
"tags": ["Endpoints"],
"summary": doc_data.get("summary", ""),
"description": doc_data.get("description", ""),
"operationId": f"{method}_{path}",
"parameters": [],
"responses": {
"200": {
"description": "Successful Response",
},
},
}
path_item[method.lower()] = operation
openapi["paths"][path] = path_item
return openapi
# Sample usage
if __name__ == "__main__":
# Mockup documentation as generated from Hug framework
hug_documentation = {
"overview": "This is an example API",
"version": "1.0.0",
"handlers": {
"/example": {
"GET": {
"summary": "Retrieve example data",
"description": "This endpoint retrieves example data from the server."
},
"POST": {
"summary": "Submit example data",
"description": "This endpoint allows you to submit example data to the server."
}
}
}
}
openapi_document = convert_to_openapi(hug_documentation)
print(yaml.dump(openapi_document, default_flow_style=False))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment