apigateway
Lambda event
- class awsmate.apigateway.LambdaProxyEvent(event_object: dict)
Bases:
LambdaEventMapping of the input event received by an AWS Lambda function triggered by AWS API Gateway and integrated in AWS_PROXY mode.
- Parameters:
event_object (dict) – The parameter
eventreceived by the AWS Lambda function handler.- Raises:
TypeError – If
event_objectis not adict.
Examples
>>> def lambda_handler(raw_event, context): >>> from awsmate.apigateway import LambdaProxyEvent >>> event = LambdaProxyEvent(raw_event)
- source_ip() IPv4Address | IPv6Address
Returns the source IP address of the API call.
- Returns:
The IP address the API call comes from.
- Return type:
ipaddress.IPv4Address or ipaddress.IPv6Address
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.identity.sourceIpkey is present in the event data or if the IP address is invalid.
Examples
>>> event.source_ip() IPv4Address('93.184.216.34')
- http_headers() Dict[str, str]
Returns all HTTP headers of the API call.
Header names are always returned in lower case. Values of these headers are returned unparsed, as submitted.
- Returns:
Keys: header names as
str. Values: corresponding raw values asstr.- Return type:
dict
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
headerskey is present in the event data.
Examples
>>> event.http_headers() {'accept': 'application/json', 'accept-encoding': 'gzip,identity'}
- http_method() str
Returns the HTTP method of the API call.
The method verb is always returned in upper case. GET, PUT, POST, PATCH, DELETE are expected, but no verification is performed.
- Returns:
HTTP method of the API call.
- Return type:
str
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.httpMethodkey is present in the event data.
Examples
>>> event.http_method() 'GET'
- http_protocol() str
Returns the HTTP protocol of the API call.
The protocol is always returned in upper case.
- Returns:
HTTP protocol of the API call.
- Return type:
str
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.protocolkey is present in the event data.
Examples
>>> event.http_protocol() 'HTTP/1.1'
- http_user_agent() str
Returns the HTTP user-agent of the API call.
The user-agent is returned as transmitted by AWS API Gateway.
- Returns:
HTTP user-agent of the API call.
- Return type:
str
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.identity.userAgentkey is present in the event data.
Examples
>>> event.http_user_agent() 'curl/7.83.1'
- header_sorted_preferences(header: str) Tuple[str, ...]
Returns all values assigned to the given header, sorted by decreasing preferences.
Preferences are determined according to the weighted quality value syntax. An empty
tupleis returned if the given header is not found among those submitted by the caller.- Returns:
Header values as
str, in decreasing preference order.- Return type:
tuple
Examples
Given the header
Accept-Encoding: gzip;q=0.2,deflate,identity;q=0.9:>>> event.header_sorted_preferences('Accept-Encoding') ('deflate', 'identity', 'gzip')
- query_domain_name() str
Returns the domain name of the API call.
The domain name is always returned in lower case.
- Returns:
Domain name of the API call.
- Return type:
str
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.domainNamekey is present in the event data.
Examples
>>> event.query_domain_name() 'example.com'
- query_path() Tuple[str, ...]
Returns the path of the API call, broken down into elements.
- Returns:
Path elements as
str.- Return type:
tuple
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContext.pathkey is present in the event data.
Examples
Given the API call
GET /projects/foobar/modules>>> event.query_path() ('projects', 'foobar', 'modules')
- query_string_parameters() Dict[str, str]
Returns all URL parameters of the API call.
Values of these parameters are returned as transmitted by AWS API Gateway. An empty
dictis returned if no parameters were submitted by the caller.- Returns:
Keys: parameter names as
str. Values: corresponding raw values asstr.- Return type:
dict
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
queryStringParameterskey is present in the event data. No parameters is supposed to be represented as'queryStringParameters': None.
Examples
Given the API call
GET '/reports?from_date=2020-01-01&to_date=2023-03-01'>>> event.query_string_parameters() {'from_date': '2020-01-01', 'to_date': '2023-03-01'}
- query_string() str
Convenience function that returns the HTTP method of the call followed by the URL of the call.
- Returns:
The query string of the API call, including URL parameters if any.
- Return type:
str
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If at least one of the
httpMethod,query_domain,query_pathorquery_string_parameterskeys is not present in the event data.
Examples
Given the API call
curl -X GET 'https://api.example.com/billing/reports?from_date=2020-01-01&to_date=2023-03-01'>>> event.query_string() 'GET https://api.example.com/billing/reports?from_date=2020-01-01&to_date=2023-03-01'
- query_payload() Dict[str, Any]
Returns the data sent as the body of the API call.
Data is expected to be valid JSON.
- Returns:
Data sent as the body of the API call loaded as a
dict,Noneif body is null.- Return type:
dict
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
bodykey is present in the event data.MalformedPayloadError – If the submitted data is not valid JSON.
Examples
>>> event.query_payload() {'some_key': 5, 'some_other_key': [1, 2, 3, 4, 5]}
- authorizer_claims() Dict[str, Any] | None
Returns the authenticated user details or
Noneif this is an anonymous API call.- Returns:
User details or
Noneif this call is anonymous.- Return type:
dict
- Raises:
awsmate.lambdafunction.AwsEventSpecificationError – If no
requestContextkey is present in the event data, or if claims is notNoneand not adict.
Examples
>>> event.authorizer_claims() {'cognito:username': '192837645', 'email': 'jane@example.com', 'given_name': 'Jane', 'family_name': 'Doe'}
HTTP responses builders
- awsmate.apigateway.build_http_response(status: int, payload: dict | str, *, event: LambdaProxyEvent | None = None, custom_transformers: Dict[str, Callable[[dict], Tuple[str, str]]] | None = None, extra_headers: Dict[str, str] | None = None) dict
Builds the HTTP response the Lambda handler has to return to API Gateway.
Should the
Acceptheader of the API call lead to aHttpNotAcceptableError, an error message is returned instead of the passed payload and the status code is set accordingly.This function handles the
Accept-Encoding: gzipheader of the API call for you. It also sets the base-64 flag of the response toTrueif the returnedContent-Typeis binary.- Parameters:
status (int) – The HTTP status code.
payload (dict or str) – The payload that constitutes the body of the response. Should it be a
str, it will first be transformed bysimple_message().event (LambdaProxyEvent) – Optional wrapper of the event the Lambda handler receives from the API Gateway.
custom_transformers (dict) – Optional mapping of
Content-Typeto transformer functions returning (the content asContent-Type, theContent-Typewith encoding asstr).extra_headers (dict) – Optional extra headers to return. For example :
{ 'Access-Control-Allow-Origin': '*' }to handle CORS.
- Returns:
The HTTP response to return to API Gateway.
- Return type:
dict
Examples
>>> payload = { >>> 'someKey': 'someVal' >>> } >>> >>> event = None # Use defaults: no specific headers ('Accept: */*' assumed), no body, no URL parameters >>> >>> custom_transformers = None # 'application/json' transformer is built-in and is bound to 'Accept: */*'. We don't need anything else here. >>> >>> extra_headers = { >>> 'Access-Control-Allow-Origin': '*' # Deals with CORS provided HTTP OPTIONS is dealt with on API Gateway side. >>> } >>> >>> build_http_response(200, payload, event=event, custom_transformers=custom_transformers, extra_headers=extra_headers) {'isBase64Encoded': False, 'statusCode': 200, 'body': '{\n "someKey": "someVal"\n}', 'headers': {'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*'}}
See also
determine_content_typemore details on the use of the optional parameter
custom_transformers.
- awsmate.apigateway.build_http_server_error_response(error: HttpServerError, *, client_message: str | None = None, log: bool = True, **kwargs: Any) dict
Convenience function that builds an HTTP error 5XX response to be returned to API Gateway by the Lambda handler.
Unless specified otherwise, calling this function logs a stack trace of the error showing the status and the actual error message. This message is replaced by a client-oriented message in the HTTP response.
- Parameters:
error (HttpServerError) – Object representing the error.
client_message (str) – Optional client-oriented message. An english canned message is used if omitted.
log (bool) – Optional flag that defines whether a stack trace should be logged.
Trueif omitted.**kwarg (any) – Optional arguments to pass to
build_http_response()
- Returns:
The HTTP error 5XX response to return to API Gateway.
- Return type:
dict
Examples
>>> build_http_server_error_response(HttpInsufficientStorageError(), client_message='Sorry, we have an issue.') {'isBase64Encoded': False, 'statusCode': 507, 'body': '{\n "Message": "Sorry, we have an issue."\n}', 'headers': {'Content-Type': 'application/json; charset=utf-8'}}
Notes
This function simply calls
>>> build_http_response(error.status, client_message, **kwargs)
It is a good idea to make your Lambda handler to catch all unexpected errors to return a clean user-oriented error message should anything go wrong.
>>> def lambda_handler(raw_event, context): >>> import awsmate.apigateway as amag >>> >>> event = amag.LambdaProxyEvent(raw_event) >>> >>> try: >>> # Everything you need to do >>> >>> return amag.build_http_response(200, "OK", event=event) >>> >>> except amag.HttpClientError as err: >>> return amag.build_http_client_error_response(err, event=event) >>> except Exception: >>> # We will end up here should any unexpected error occur >>> return amag.build_http_server_error_response(amag.HttpInternalServerError(), event=event)
- awsmate.apigateway.build_http_client_error_response(error: HttpClientError, *, log: bool = True, **kwargs: Any) dict
Convenience function that builds an HTTP error 4XX response to be returned to API Gateway by the Lambda handler.
Unless specified otherwise, calling this function logs an error showing the status and message.
- Parameters:
error (HttpClientError) – Object representing the error.
log (bool) – Optional flag that defines whether a stack trace should be logged.
Trueif omitted.**kwarg (any) – Optional arguments to pass to
build_http_response()
- Returns:
The HTTP error 4XX response to return to API Gateway.
- Return type:
dict
Examples
>>> build_http_client_error_response(HttpNotFoundError()) {'isBase64Encoded': False, 'statusCode': 404, 'body': '{\n "Message": "Not Found"\n}', 'headers': {'Content-Type': 'application/json; charset=utf-8'}}
Notes
This function simply calls
>>> build_http_response(error.status, str(error), **kwargs)
It is a good idea to make your Lambda handler to catch all HttpClientError to return a clean error message should there be any problem with the request.
>>> def lambda_handler(raw_event, context): >>> import awsmate.apigateway as amag >>> >>> event = amag.LambdaProxyEvent(raw_event) >>> >>> try: >>> # Everything you need to do >>> >>> return amag.build_http_response(200, "OK", event=event) >>> >>> except amag.HttpClientError as err: >>> return amag.build_http_client_error_response(err, event=event) # We will end up here should anything be wrong in the client's request >>> except Exception: >>> return amag.build_http_server_error_response(amag.HttpInternalServerError(), event=event)
HTTP errors
Base classes
- exception awsmate.apigateway.HttpError(status: int, msg: str)
Bases:
RuntimeErrorHTTP error response: status code and message.
Examples
>>> raise HttpError(404, 'Not Found')
- Parameters:
status (int) – The HTTP response status code. This value is taken as-is, there is no validation routine.
msg (str) – The explanatory message.
- property status: int
HTTP response status code.
Examples
Given
e = HttpError(403, 'Forbidden')>>> e.status 403
- Type:
int
- exception awsmate.apigateway.HttpClientError(status: int, msg: str)
Bases:
HttpErrorClient HTTP error response.
Examples
>>> raise HttpClientError(404, 'Not Found')
- Parameters:
status (int) – The HTTP response status code. This value is taken as-is, there is no validation routine.
msg (str) – The explanatory message.
- exception awsmate.apigateway.HttpServerError(status: int, msg: str)
Bases:
HttpErrorServer-side HTTP error response.
Examples
>>> raise HttpServerError(503, 'Service Unavailable')
- Parameters:
status (int) – The HTTP response status code. This value is taken as-is, there is no validation routine.
msg (str) – The explanatory message.
Client errors
- exception awsmate.apigateway.HttpBadRequestError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 400 “Bad request”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpBadRequestError()
- exception awsmate.apigateway.HttpUnauthorizedError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 401 “Unauthorized”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpUnauthorizedError()
- exception awsmate.apigateway.HttpPaymentRequiredError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 402 “Payment required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpPaymentRequiredError()
- exception awsmate.apigateway.HttpForbiddenError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 403 “Forbidden”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpForbiddenError()
- exception awsmate.apigateway.HttpNotFoundError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 404 “Not found”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpNotFoundError()
- exception awsmate.apigateway.HttpMethodNotAllowedError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 405 “Method not allowed”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpMethodNotAllowedError()
- exception awsmate.apigateway.HttpNotAcceptableError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 406 “Not acceptable”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpNotAcceptableError()
- exception awsmate.apigateway.HttpProxyAuthenticationRequiredError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 407 “Proxy authentication required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpProxyAuthenticationRequiredError()
- exception awsmate.apigateway.HttpRequestTimeoutError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 408 “Request timeout”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRequestTimeoutError()
- exception awsmate.apigateway.HttpConflictError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 409 “Conflict”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpConflictError()
- exception awsmate.apigateway.HttpGoneError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 410 “Gone”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpGoneError()
- exception awsmate.apigateway.HttpLengthRequiredError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 411 “Length required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpLengthRequiredError()
- exception awsmate.apigateway.HttpPreconditionFailedError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 412 “Precondition failed”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpPreconditionFailedError()
- exception awsmate.apigateway.HttpRequestEntityTooLargeError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 413 “Request entity too large”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRequestEntityTooLargeError()
- exception awsmate.apigateway.HttpRequestUriTooLongError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 414 “Request URI too long”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRequestUriTooLongError()
- exception awsmate.apigateway.HttpUnsupportedMediaTypeError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 415 “Unsupported media type”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpUnsupportedMediaTypeError()
- exception awsmate.apigateway.HttpRequestRangeNotSatisfiableError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 416 “Request range not satisfiable”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRequestRangeNotSatisfiableError()
- exception awsmate.apigateway.HttpExpectationFailedError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 417 “Expectation failed”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpExpectationFailedError()
- exception awsmate.apigateway.HttpMisdirectedRequestError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 421 “Misdirected request”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpMisdirectedRequestError()
- exception awsmate.apigateway.HttpUnprocessableEntityError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 422 “Unprocessable entity”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpUnprocessableEntityError()
- exception awsmate.apigateway.HttpLockedError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 423 “Locked”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpLockedError()
- exception awsmate.apigateway.HttpFailedDependencyError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 424 “Failed dependency”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpFailedDependencyError()
- exception awsmate.apigateway.HttpUpgradeRequiredError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 426 “Upgrade required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpUpgradeRequiredError()
- exception awsmate.apigateway.HttpPreconditionRequiredError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 428 “Precondition required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpPreconditionRequiredError()
- exception awsmate.apigateway.HttpTooManyRequestsError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 429 “Too many requests”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpTooManyRequestsError()
- exception awsmate.apigateway.HttpRequestHeaderFieldsTooLargeError(msg: str | None = None)
Bases:
HttpClientErrorError that represents a HTTP response status 431 “Request header fields too large”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRequestHeaderFieldsTooLargeError()
Server-side errors
- exception awsmate.apigateway.HttpInternalServerError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 500 “Internal server error”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpInternalServerError()
- exception awsmate.apigateway.HttpNotImplementedError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 501 “Not implemented”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpNotImplementedError()
- exception awsmate.apigateway.HttpBadGatewayError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 502 “Bad gateway”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpBadGatewayError()
Bases:
HttpServerErrorError that represents a HTTP response status 503 “Service unavailable”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpRServiceUnavailableError()
- exception awsmate.apigateway.HttpGatewayTimeoutError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 504 “GatewayTimeout”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpGatewayTimeoutError()
- exception awsmate.apigateway.HttpVersionNotSupportedError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 505 “HTTP version not supported”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpVersionNotSupportedError()
- exception awsmate.apigateway.HttpVarianteAlsoNegociatesError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 506 “Variant also negociates”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpVarianteAlsoNegociatesError()
- exception awsmate.apigateway.HttpInsufficientStorageError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 507 “Insufficient storage”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpInsufficientStorageError()
- exception awsmate.apigateway.HttpLoopDetectedError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 508 “Loop detected””.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpLoopDetectedError()
- exception awsmate.apigateway.HttpNotExtendedError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 510 “Not extended”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpNotExtendedError()
- exception awsmate.apigateway.HttpNetworkAuthenticationRequiredError(msg: str | None = None)
Bases:
HttpServerErrorError that represents a HTTP response status 511 “Network authentication required”.
- Parameters:
msg (str) – Explanatory message. A default message is used if omitted.
Examples
>>> raise HttpNetworkAuthenticationRequiredError()
Helper functions
- awsmate.apigateway.simple_message(message: str) Dict[str, str]
Turns a
strinto adictpayload having “Message” as a key and the passed string as a value.build_http_response()uses this function to build response payloads from strings.There is no need to call
simple_message()directly normally, although it may not cause any harm.- Parameters:
message (str) – The string to turn into a message payload.
- Returns:
Payload built from the message string.
- Return type:
dict
Examples
>>> simple_message("This is fine!") {'Message': 'This is fine!'}
- awsmate.apigateway.determine_content_type(event: LambdaProxyEvent, *, custom_transformers: Dict[str, Callable[[dict], Tuple[str, str]]] | None = None) str
Determines the
Content-Typeof the response to be sent based on theAcceptheader of the request.application/jsonis the onlyContent-Typetransformer available by default. It is mapped to theAcceptvalues*/*,application/*andapplication/json. Any otherAcceptvalue leads to aHttpNotAcceptableErrorunlesscustom_transformersmap thisAcceptvalue to an appropriate transformer.Preferences are handled by
LambdaProxyEvent.header_sorted_preferences(). Should noAcceptheader be given,*/*is assumed.- Parameters:
event (LambdaProxyEvent) – The API call event.
custom_transformers (dict) – Optional mapping of
Content-Typeto transformer functions returning (the content asContent-Type, theContent-Typewith encoding asstr).
- Returns:
The
Content-Typeof the response.- Return type:
str
- Raises:
HttpNotAcceptableError – If no transformer meets the criteria of the
Acceptheader.
Examples
Given an API call that was made with a
Accept: */*header, with no custom format handled by the application:>>> determine_content_type(event) 'application/json'
Given an API call that was made with a
Accept: text/csvheader, with an application handlingtext/csvandapplication/xmlon top of the defaultapplication/json:>>> def csv_transformer(payload: dict) -> typing.Tuple[str, str]: >>> # ... code that converts the json payload to csv and stores it into a variable called csvContent ... >>> return csvContent, 'text/csv; charset=utf-8' >>> >>> def xml_transformer(payload: dict) -> typing.Tuple[str, str]: >>> # ... code that converts the json payload to xml and stores it into a variable called xmlContent ... >>> return xmlContent, 'application/xml; charset=utf-8' >>> >>> custom_transformers = { >>> 'text/csv': csv_transformer, >>> 'application/xml': xml_transformer >>> } >>> >>> determine_content_type(event, custom_transformers=custom_transformers) 'text/csv'
Notes
It is a good idea to call this function at the very beginning of your Lambda handler. This way you can make sure that the accepted
Content-Typematches what your API is capable of returning, and return anHttpNotAcceptableErrorresponse without doing any unnecessary processing otherwise.The example below only accepts
*/*,application/*andapplication/json, all mapped toapplication/jsonby default.>>> def lambda_handler(raw_event, context): >>> import awsmate.apigateway as amag >>> >>> event = amag.LambdaProxyEvent(raw_event) >>> >>> try: >>> amag.determine_content_type(event) >>> >>> # Everything you need to do >>> >>> return amag.build_http_response(200, "OK", event=event) >>> >>> except amag.HttpClientError as err: >>> return amag.build_http_client_error_response(err, event=event) # We will end up here should HttpNotAcceptableError be raised by determine_content_type() >>> except Exception: >>> return amag.build_http_server_error_response(amag.HttpInternalServerError(), event=event)
- awsmate.apigateway.is_binary(content_type: str) bool
Determines whether the given
Content-Typeis binary.build_http_response()uses this function to determine if the API Gateway requires abase64encoding prior returning the content. All types buttext/*,application/xmlandapplication/jsonare considered binary.There is no need to call
is_binary()directly normally, although it may not cause any harm.- Parameters:
content_type (str) – The
Content-Typeto assess.- Returns:
Whether the
Content-Typeis binary.- Return type:
bool
Examples
>>> is_binary('image/jpeg') True
- awsmate.apigateway.json_transformer(payload: dict) Tuple[str, str]
Transformer used by
build_http_response()to buildapplication/jsonresponses.There is no need to this function directly normally, although it may not cause any harm.
- Parameters:
payload (dict) – The payload to convert to
application/json.- Returns:
The
application/jsonpayload as astr, theContent-Typewith its encoding specifier.- Return type:
tuple
Examples
>>> json_transformer({'TopThreeBibs': (751,25,372)}) ('{\n "TopThreeBibs": [\n 751,\n 25,\n 372\n ]\n}', 'application/json; charset=utf-8')