Java
Chilkat2 Java
Call an AWS Lambda Function
See more AWS Misc Examples
Demonstrates how to call an AWS Lambda function.Chilkat Java Downloads
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.StringBuilder;
public class ChilkatExample {
public static void main(String[] args) {
// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
Rest rest = new Rest();
// Connect to the Amazon AWS REST server.
// such as https://email.us-west-2.amazonaws.com/
boolean bTls = true;
int port = 443;
boolean bAutoReconnect = true;
// -------------------------------------------------------------------------------------------
// Note: The source of the lambda function (hosted on AWS) is shown at the bottom of this page.
// --------------------------------------------------------------------------------------------
// If your lambda function URL is: https://itwxyj3vd6gjtaerbfqnfccs2e0fplzh.lambda-url.us-west-2.on.aws/
// then use just the domain part here:
rest.connect("itwxyj3vd6gjtaerbfqnfccs2e0fplzh.lambda-url.us-west-2.on.aws", port, bTls, bAutoReconnect);
// Provide AWS credentials for the REST call.
AuthAws authAws = new AuthAws();
authAws.setAccessKey("AWS_ACCESS_KEY");
authAws.setSecretKey("AWS_SECRET_KEY");
// the region should match our domain above..
authAws.setRegion("us-west-2");
authAws.setServiceName("lambda");
rest.setAuthAws(authAws);
JsonObject json = new JsonObject();
json.updateString("name", "Benny");
rest.addHeader("Content-Type", "application/json");
StringBuilder sbRequestBody = new StringBuilder();
json.emitSb(sbRequestBody);
StringBuilder sbResponseBody = new StringBuilder();
try {
rest.fullRequestSb("POST", "/", sbRequestBody, sbResponseBody);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
int statusCode = rest.getResponseStatusCode();
if (statusCode >= 400) {
System.out.println("Response Status Code: " + statusCode);
System.out.println("Response Body: " + sbResponseBody.getAsString());
System.out.println("Failed.");
return;
}
System.out.println("Response Body:");
System.out.println(sbResponseBody.getAsString());
}
}
JavaScript
export const handler = async (event) => {
let body = "Hello World";
if (event.body) {
const input = JSON.parse(event.body);
if (input.name) {
body = "Hello " + input.name;
}
}
return {
statusCode: 200,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
message: body
})
};
};