Invoke Lambda Directly

Invoke protector lambda function directly (without API Gateway)

AWS Lambda can be invoked directly, such as from AWS SDK. This section contains information about request and response payloads with examples demonstrating direct invocation using AWS CLI and Python SDK (Boto3).

Request Payload

Lambda request payload for the direct invocation is defined as following

{
  "body": "<rest-api-request-payload>",
  "path": "/v1/<operation>",
  "headers": {}
}
  • body - JSON string. Request schemas defined in Rest API Request.
  • path - can be either ‘/v1/protect’ or ‘/v1/unprotect’.
  • headers - can be used to pass authorization headers. See example below.

Example request:

{
  "body": "{\"query_id\": \"3\",\"user\": \"user1\",\"data_element\": \"deAlpha\",\"data\": [\"data1\", \"data2\"]}",
  "path": "/v1/protect",
  "headers": {}
}

Example Request with JWT authorization:

{
  "body": "{\"query_id\": \"3\",\"user\": \"user1\",\"data_element\": \"deAlpha\",\"data\": [\"data1\", \"data2\"]}",
  "path": "/v1/protect",
  "headers": {
    "authorization": "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTM4NjIzNzEsImlkIjoiYS1iLWMtZC1lLWYtMS0yLTMiLCJ1c2VybmFtZSI6IlBhdWwgQXRyZWlkZXMifQ.R1NcJ43540HKdhEBOK9WaMMpjBOYSJetckQKrcPQdz0z6sx1EDwHXYngBP9DtHgUM-6Vf1VNjtFh_Nqfeepp1BavmigIXoe3ZbrxRI3DFKi2UuLmgn--EYrSGlWsQjnmjaz5qUkID9iY2MtsRunKSuolSvG9UsD1G32kv0KZYX0"
  }
}

Response Payload

Lambda response payload has the following structure

{
  "body": "<rest-api-response-payload>"
  "isBase64Encoded": false,
  "statusCode": <http-status-code>,
}
  • body - JSON string. Response schemas defined in Rest API Response.
  • isBase64Encoded - always set to false.
  • statusCode - HTTP status code integer.

Success Response Payload Example:

{
  "body": "{\"encoding\":\"utf8\",\"results\":[\"xcgd\", \"migs\"],\"success\":true}", 
  "isBase64Encoded": false, 
  "statusCode": 200
}

Error Response

Cloud API Lambda returns following error responses depending on the error type

Cloud API Protection Operation Error
      Returned when invalid data element is used or user has insufficient permissions to execute security operation.

{
  "body": "{\"error_msg\":\"Unprotect failed. Data element not found. Refer to audit log for details.\",\"success\":false}", 
  "isBase64Encoded": false, 
  "statusCode": 400
}

Cloud API Invalid Request Error
      Missing fields in the incoming request or malformed request JSON.

{
  "body": "Request format is not supported", 
  "isBase64Encoded": false, 
  "statusCode": 400
}

Cloud API Unexpected Lambda Exception Error
      Caused by Lambda runtime exception, for instance due to too short timeout or not enough memory.

{
  "errorMessage": "2023-01-18T16:42:19.593Z d0cf62d0-9eaf-427b-8ca5-1bdd8bd0b082 Task timed out after 10.25 seconds"
}

Examples

Prerequisites:

  • AWS SDK or Command Line
  • AWS Access Key ID and AWS Access Key

See Request Payload for request payload examples.

AWS CLI command to invoke Cloud API Lambda function:

aws lambda invoke --function-name Protegrity_Protect_RESTAPI_{stackname} --payload
    fileb://request_payload.json --log-type Tail output

    
  

Sample Python code demonstrating Cloud API Direct Lambda Calls

import json
import logging
import boto3
lambda_client = boto3.client("lambda")
logging.basicConfig(format="%(message)s")
logger = logging.getLogger('pty_cloud_api_sample')
logger.setLevel(logging.DEBUG)


class ProtectClient(object):
  """ 
    Sample client demonstrating how to invoke Protegrity Cloud API Lambda

      protect_fn: str - Name of the Cloud API Lambda (for example, Protegrity_Protect_RESTAPI_my_deployment)
  """

  def __init__(self, protect_fn):
    self.protect_fn = protect_fn

  def invoke_protect(self, values, data_element, operation, user, query_id,
              column_info=""):
    """ 
    Invokes Protegrity Cloud API Lambda to execute protect or unprotect operation

      values: list[str] - List of values to be protected/unprotected
      data_element: str - Name of the policy data element to use with protect/unprotect operation
      operation: str - Either 'protect' or 'unprotect'
      user: str - Policy user
      query_id: str - Query id will be present in the audit log
      column_info: - Used for troubleshooting, for instance, when protecting values/rows from multiple database columns
    """

    # Set authorization header here if JWT authorization is 
    # enabled in Cloud API Function configuration
    headers = {"Authorization": ""}
    request_body = {
      "user": user,
      "data_element": data_element,
      "data": values,
      "query_id": query_id
    }
    payload = json.dumps({"body": json.dumps(request_body), "path": f"/v1/{operation}",
                  "headers": headers})
    logger.debug(f"Request payload: {payload}")
    response = lambda_client.invoke(FunctionName=self.protect_fn, Payload=payload)
    lambda_response_payload = json.loads(response["Payload"].read().decode())
    logger.debug(f"Response payload: {lambda_response_payload}")
    response_status_code = lambda_response_payload.get("statusCode")
    response_body_string = lambda_response_payload.get("body")
    if response_status_code == None or response_body_string == None:
      raise Exception(f"Unexpected Cloud API Lambda error: [{lambda_response_payload}]")
    try:
      body_json = json.loads(response_body_string)
      if response_status_code == 200:
        return body_json.get("results", [])
      elif body_json.get("error_msg"):
        raise Exception(f"Cloud API Lambda error: [{response_status_code} - {body_json.get('error_msg')}]")
      raise Exception(f"Unexpected Cloud API Lambda error: [{lambda_response_payload}]")
    except json.decoder.JSONDecodeError:
      # Cloud API may return error in the response body
      # For example, {"statusCode": 400, "body":"Error message"}
      raise Exception(f"Cloud API Lambda error: [{response_status_code} - {response_body_string}]")

# Replace cloud-api-lambda-name with the name of the Cloud API Lambda
# For example, Protegrity_Protect_RESTAPI_my_deployment
protect_client = ProtectClient('cloud-api-lambda-name')
protected_data = ["UtfVk UHgcD!"]
logger.info(f"Protected data: {protected_data}")
unprotected_data = protect_client.invoke_protect(
  values=protected_data, 
  data_element='alpha', 
  operation='unprrotect', 
  user='test-user', 
  query_id='1234')
logger.info(f"Unprotected data: {unprotected_data}")

Last modified : December 02, 2025