APIG Event Source¶
API Gateway (APIG) is an API hosting service that helps enterprises to build, manage, and deploy APIs at any scale. With APIG, your function can be invoked through HTTPS by using a custom REST API and a specified backend. You can map each API operation (such as, GET and PUT) to a specific function. APIG invokes the relevant function when an HTTPS request is sent to the API backend.
For more information about how to use HTTPS calls to trigger functions, see Using an APIG (Dedicated) trigger.
Example APIG Event¶
{
"body": "eyJuYW1lIjogIk9wZW5UZWxla29tQ2xvdWQifQ==",
"requestContext": {
"apiId": "bc1dcffd-aa35-474d-897c-d53425a4c08e",
"requestId": "11cdcdcf33949dc6d722640a13091c77",
"stage": "RELEASE"
},
"queryStringParameters": {
"responseType": "html"
},
"httpMethod": "GET",
"pathParameters": {},
"headers": {
"accept-language": "q=0.5,en-US;q=0.3,en;q=0.2",
"accept-encoding": "gzip, deflate, br",
"x-forwarded-port": "443",
"x-forwarded-for": "103.218.216.98",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"upgrade-insecure-requests": "1",
"host": "host",
"x-forwarded-proto": "https",
"pragma": "no-cache",
"cache-control": "no-cache",
"x-real-ip": "103.218.216.98",
"user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0"
},
"path": "/",
"isBase64Encoded": true
}
Parameter description¶
Parameter |
Type |
Description |
|---|---|---|
body |
String |
Actual request body in string format (Base64 encoded). |
requestContext |
Map |
Request information, including the API gateway configuration, request ID, authentication information, and source. |
httpMethod |
String |
HTTP method |
queryStringParameters |
Map |
Query strings configured in APIG and their actual values |
pathParameters |
Map |
Path parameters configured in APIG and their actual values |
headers |
Map |
Complete headers |
path |
String |
Complete path |
isBase64Encoded |
Boolean |
Default value: true (see Notes below) |
Notes¶
When calling a function using APIG, isBase64Encoded is valued true by default, indicating that the request body transferred to FunctionGraph is encoded using Base64 and must be decoded for processing.
The function must return characters strings by using the following structure.
{ "isBase64Encoded": "true|false", "statusCode": "httpStatusCode", "headers": {"headerName":"headerValue"}, "body": "..." }
Note
For asynchronous invocation, of FunctionGraph, select the APIG trigger and click its name to go to the APIG console, and select Asynchronous for the Invocation Mode. For details, see
Asynchronous Invocation in user manual and
Configuring Backend Settings in API gateway user manual
Example¶
import json
from fg_apig_event import APIGEvent, APIGResponse
def handler(event, context):
logger = context.getLogger()
logger.info("Function Name: %s", context.getFunctionName())
apig_event = APIGEvent(event)
is_base64_encoded = apig_event.is_base64_encoded() or False
body = apig_event.get_body()
logger.info("APIG Event body: %s", body)
response_type = apig_event.get_query_string_parameter("responseType")
if response_type == "html":
output = APIGResponse(
200,
"",
{"Content-Type": "text/html; charset=utf-8"},
False,
)
output.set_body(
"<html><h1>Welcome to use FunctionGraph</h1></html>",
is_base64_encoded,
)
elif response_type == "json":
output = APIGResponse(
200,
"",
{"Content-Type": "application/json"},
False,
)
try:
parsed_body = json.loads((body or "").replace('\\"', '"'))
output.set_body(parsed_body, is_base64_encoded)
except (json.JSONDecodeError, TypeError):
output.set_body({"error": "Invalid JSON input"}, is_base64_encoded)
else:
output = APIGResponse(
200,
"",
{"Content-Type": "text/html; charset=utf-8"},
False,
)
output.set_body(
"<html>Please construct the url with query parameters responseType=html, responseType=json</html>",
is_base64_encoded,
)
logger.info("returning: %s", output)
return output
Full sample code is available in the samples-doc/scratch-event-apig.
Package description¶
Public package exports for fg_apig_event.
- class fg_apig_event.APIGEvent(event)¶
Bases:
objectRepresents an API Gateway event for FunctionGraph.
- Attributes:
body (str): The request body
isBase64Encoded (bool): Whether the body is base64 encoded
requestContext (dict): Request context information
queryStringParameters (dict): Query string parameters
httpMethod (str): HTTP method
pathParameters (dict): Path parameters
headers (dict): Request headers
path (str): Request path
Initialize APIGEvent.
- Args:
event (dict): The API Gateway event data
- get_body()¶
Returns the decoded request body.
- Returns:
str: Body content in plain text
- get_raw_body()¶
Returns the raw request body.
- Returns:
str: Body content as received
- get_request_context()¶
Returns the request context.
- Returns:
APIGRequestContext: The request context object
- get_request_context_value(key)¶
Get a value from the request context by key.
- Args:
key (str): The key to retrieve
- Returns:
str: The value or empty string if not found
- get_query_string_parameters()¶
Returns the query string parameters.
- Returns:
dict: Query string parameters
- get_query_string_parameter(param_name)¶
Get a query string parameter by name.
- Args:
param_name (str): The parameter name
- Returns:
str: The parameter value or empty string if not found
- get_http_method()¶
Returns the HTTP method.
- Returns:
str: The HTTP method
- get_path_parameters()¶
Returns the path parameters.
- Returns:
dict: Path parameters
- get_path_parameter(param_name)¶
Get a path parameter by name.
- Args:
param_name (str): The parameter name
- Returns:
str: The parameter value or empty string if not found
- get_headers()¶
Returns the request headers.
- Returns:
dict: Request headers
- get_header(header_name)¶
Get a header value by name.
- Args:
header_name (str): The header name
- Returns:
str: The header value or empty string if not found
- get_path()¶
Returns the request path.
- Returns:
str: The request path
- is_base64_encoded()¶
Returns whether the body is base64 encoded.
- Returns:
bool: True if base64 encoded, False otherwise
- to_json()¶
Returns the event as a dictionary.
- Returns:
dict: The raw event data
- class fg_apig_event.APIGRequestContext(request_context)¶
Bases:
objectRepresents the request context of an API Gateway event.
- Attributes:
apiId (str): The API ID requestId (str): The request ID stage (str): The stage
Initialize APIGRequestContext.
- Args:
request_context (dict): The request context data
- get_api_id()¶
Returns the API ID.
- Returns:
str: The API ID
- get_request_id()¶
Returns the request ID.
- Returns:
str: The request ID
- get_stage()¶
Returns the stage.
- Returns:
str: The stage
- get_value(key)¶
Get a value from the request context by key.
- Args:
key (str): The key to retrieve
- Returns:
str: The value or None if not found
- to_json()¶
Returns the request context as a dictionary.
- Returns:
dict: The raw request context data
- class fg_apig_event.APIGResponse(status_code=200, body='', headers=None, is_base64_encoded=False)¶
Bases:
objectRepresents an API Gateway response for FunctionGraph.
- Attributes:
statusCode (int): HTTP status code body (str): Response body headers (dict): Response headers isBase64Encoded (bool): Whether the body is base64 encoded
Initialize APIGResponse.
- Args:
status_code (int, optional): HTTP status code. Defaults to 200. body (str, optional): Response body. Defaults to “”. headers (dict, optional): Response headers. Defaults to {}. is_base64_encoded (bool, optional): Whether body is base64 encoded. Defaults to False.
- classmethod from_json(data)¶
Create an APIGResponse from a dictionary.
- Args:
data (dict): Dictionary with response data
- Returns:
APIGResponse: A new APIGResponse instance
- set_status_code(status_code)¶
Set the HTTP status code.
- Args:
status_code (int): The HTTP status code
- set_body(body, is_base64_encoded=False)¶
Set the response body.
- Args:
body (str or dict): The body content is_base64_encoded (bool, optional): Whether to encode as base64. Defaults to False.
- get_raw_body()¶
Returns the raw response body.
- Returns:
str: The body as stored
- get_body()¶
Returns the decoded response body.
- Returns:
str: The body content in plain text
- get_body_parsed()¶
Returns the parsed response body as a Python object.
- Returns:
dict or str or None: The parsed body content
- to_json()¶
Returns the response as a dictionary.
- Returns:
dict: The response data