in samtranslator/plugins/api/implicit_api_plugin.py [0:0]
def _add_api_to_swagger(self, event_id, event_properties, template): # type: ignore[no-untyped-def]
"""
Adds the API path/method from the given event to the Swagger JSON of Serverless::Api resource this event
refers to.
:param string event_id: LogicalId of the event
:param dict event_properties: Properties of the event
:param SamTemplate template: SAM Template to search for Serverless::Api resources
"""
# Need to grab the AWS::Serverless::Api resource for this API event and update its Swagger definition
api_id = self._get_api_id(event_properties)
# As of right now, this is for backwards compatability. SAM fails if you have an event type "Api" but that
# references "AWS::Serverless::HttpApi". If you do the opposite, SAM still outputs a valid template. Example of that
# can be found https://github.com/aws/serverless-application-model/blob/develop/tests/translator/output/api_with_any_method_in_swagger.json.
# One would argue that, this is unexpected and should actually fail. Instead of suddenly breaking customers in this
# position, we added a check to make sure the Plugin run (Http or Rest) is referencing an api of the same type.
is_referencing_http_from_api_event = (
not template.get(api_id)
or template.get(api_id).type == "AWS::Serverless::HttpApi"
and template.get(api_id).type != self.SERVERLESS_API_RESOURCE_TYPE
)
# RestApiId is not pointing to a valid API resource
if isinstance(api_id, dict) or is_referencing_http_from_api_event:
raise InvalidEventException(
event_id,
f"{self.API_ID_EVENT_PROPERTY} must be a valid reference to an '{self.SERVERLESS_API_RESOURCE_TYPE}'"
" resource in same template.",
)
# Make sure Swagger is valid
resource = template.get(api_id)
if not (
resource
and isinstance(resource.properties, dict)
and self.EDITOR_CLASS.is_valid(resource.properties.get("DefinitionBody"))
):
# This does not have an inline Swagger. Nothing can be done about it.
return
if not resource.properties.get("__MANAGE_SWAGGER"):
# Do not add the api to Swagger, if the resource is not actively managed by SAM.
# ie. Implicit API resources are created & managed by SAM on behalf of customers.
# But for explicit API resources, customers write their own Swagger and manage it.
# If a path is present in Events section but *not* present in the Explicit API Swagger, then it is
# customer's responsibility to add to Swagger. We will not modify the Swagger here.
#
# In the future, we will might expose a flag that will allow SAM to manage explicit API Swagger as well.
# Until then, we will not modify explicit explicit APIs.
return
swagger = resource.properties.get("DefinitionBody")
path = event_properties["Path"]
method = event_properties["Method"]
editor = self.EDITOR_CLASS(swagger)
editor.add_path(path, method)
resource.properties["DefinitionBody"] = self._get_api_definition_from_editor(editor) # type: ignore[no-untyped-call]
template.set(api_id, resource)