How to Invoke AWS Lambda Function: Syntax, Example, and Tips
You can invoke an AWS Lambda function using the
aws lambda invoke command in AWS CLI or by calling the invoke method in AWS SDKs. This sends an event to the Lambda function and returns the response or status synchronously or asynchronously.Syntax
The basic syntax to invoke a Lambda function using AWS CLI is:
aws lambda invoke --function-name <FunctionName> --payload <JSONPayload> <OutputFile>
In AWS SDKs, you call the invoke method with parameters like function name, invocation type, and payload.
Parts explained:
--function-name: The name or ARN of your Lambda function.--payload: JSON input event sent to the function.OutputFile: File where the function response is saved.InvocationType: (SDK) 'RequestResponse' for sync, 'Event' for async.
bash
aws lambda invoke --function-name MyFunction --payload '{"key":"value"}' response.json
Example
This example shows how to invoke a Lambda function named MyFunction synchronously using AWS SDK for Python (boto3). It sends a JSON payload and prints the function's response.
python
import boto3 import json client = boto3.client('lambda') response = client.invoke( FunctionName='MyFunction', InvocationType='RequestResponse', Payload=json.dumps({'key': 'value'}) ) response_payload = response['Payload'].read().decode('utf-8') print('Lambda response:', response_payload)
Output
Lambda response: {"statusCode":200,"body":"Hello from Lambda!"}
Common Pitfalls
Common mistakes when invoking Lambda functions include:
- Not setting the correct
InvocationType, causing unexpected sync or async behavior. - Sending payloads that are not valid JSON strings.
- Ignoring permissions: the caller must have
lambda:InvokeFunctionpermission. - Not handling the response stream properly in SDKs.
Example of wrong and right payload usage:
python
# Wrong: payload as Python dict (will cause error) response = client.invoke( FunctionName='MyFunction', Payload={'key': 'value'} # Incorrect: must be JSON string ) # Right: payload as JSON string import json response = client.invoke( FunctionName='MyFunction', Payload=json.dumps({'key': 'value'}) )
Quick Reference
Tips for invoking Lambda functions:
- Use
RequestResponsefor synchronous calls to get immediate results. - Use
Eventfor asynchronous calls when you don't need the response. - Always validate your JSON payload before sending.
- Check IAM permissions to avoid authorization errors.
- Use AWS CLI for quick tests and SDKs for integration in code.
Key Takeaways
Invoke Lambda functions using AWS CLI or SDK by specifying function name and JSON payload.
Use 'RequestResponse' invocation type for synchronous calls and 'Event' for asynchronous calls.
Always send payloads as valid JSON strings, not raw objects.
Ensure your IAM user or role has permission to invoke the Lambda function.
Handle the response stream correctly when using SDKs to read function output.