Skip to content

Instantly share code, notes, and snippets.

@srkiNZ84
Last active August 8, 2019 11:11
Show Gist options
  • Save srkiNZ84/21a3a9fab6311064632bfbfade7caced to your computer and use it in GitHub Desktop.
Save srkiNZ84/21a3a9fab6311064632bfbfade7caced to your computer and use it in GitHub Desktop.
Python script to take OpenAPI YAML definitions and enhance them with AWS API Gateway annotations with a view to auto-generating mocks
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
####!/usr/bin/python3
import os
import yaml
class APIGW():
def __init__(self, responses, passThroughBehavior, requestTemplates,
gwType):
self.responses = responses
self.passThroughBehavior = passThroughBehavior
self.requestTemplates = requestTemplates
self.type = gwType
try:
apiDefFile = open("raw_definition.yaml", "r")
apiDefinition = yaml.safe_load(apiDefFile)
except yaml.YAMLError as exc:
print("Error parsing configuration: " + str(exc))
exit(1)
print("Loaded API def file")
for path in apiDefinition["paths"]:
print("Annotating path " + path)
for method in apiDefinition["paths"][path]:
print("..Annotating HTTP method " + method)
# TODO Check if annotations are already present and if so, no need to add
# Here we add the new values
ourResponses = {
"default": {
"statusCode": "200"
}
}
ourRequestTemplates = {
"application/json": "{\"statusCode\": 200}"
}
apigw = APIGW(ourResponses, "when_no_match", ourRequestTemplates, "mock")
apiDefinition["paths"][path][method]["x-amazon-apigateway-integration"] = apigw.__dict__
try:
apiDefFile = open("annotated_definition.yaml", "w")
yaml.dump(apiDefinition, apiDefFile, default_flow_style=False)
except Exception as exc:
print("Something went wrong writing the file out: " + str(exc))
exit(1)
openapi: "3.0.1"
info:
title: "sample blog"
version: "v1"
servers:
- url: "api.example.com"
variables:
basePath:
default: "/dev"
paths:
/:
post:
responses:
200:
description: "200 response"
content:
application/json:
schema:
$ref: "#/components/schemas/Empty"
components:
schemas:
Empty:
title: "Empty Schema"
type: "object"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment