AWS Lambda via SDK: Your First Function
AWS Lambda runs your code on demand with no servers to manage.
Busca en todas las páginas de la documentación
AWS Lambda runs your code on demand with no servers to manage.
This page uses the SDK to manage a function's whole lifecycle: create it from an inline zip, wait until it is active, invoke it, push a code update, then delete it.
You will usually create functions with IaC in real projects, but doing it by hand once makes the moving parts clear.
Quick-reference recipe card - copy-paste ready.
# --- Python (boto3) ---
import boto3, json
lam = boto3.client("lambda", region_name="us-east-1")
# Invoke an existing function and read its JSON output.
resp = lam.invoke(FunctionName="hello", Payload=json.dumps({"name": "Ada"}))
print(resp["StatusCode"], resp["Payload"].read().decode())// --- TypeScript (AWS SDK v3) ---
import { LambdaClient, InvokeCommand } from "@aws-sdk/client-lambda";
const lam = new LambdaClient({ region: "us-east-1" });
// Invoke an existing function and read its JSON output.
const resp = await lam.send(new InvokeCommand({
FunctionName: "hello",
Payload: JSON.stringify({ name: "Ada" }),
}));
console.log(resp.StatusCode, new TextDecoder().decode(resp.Payload));When to reach for this:
Zip a tiny handler in memory, create the function with an existing execution role, wait until it is active, invoke it, update its code, then delete it.
# --- Python (boto3) ---
import boto3, io, json, zipfile
lam = boto3.client("lambda", region_name="us-east-1")
def zip_handler(source: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("index.py", source)
return buf.getvalue()
# 1. Create with a zipped package and an existing execution role ARN.
lam.create_function(
FunctionName="hello",
Runtime="python3.12",
Role="arn:aws:iam::111122223333:role/lambda-basic-exec",
Handler="index.handler",
Code={"ZipFile": zip_handler(
"def handler(event, ctx):\n"
" return {'greeting': f\"hi {event.get('name','world')}\"}\n"
)},
)
# 2. Wait until the function is active, then invoke it.
lam.get_waiter("function_active_v2").wait(FunctionName="hello")
out = lam.invoke(FunctionName="hello", Payload=json.dumps({"name": "Ada"}))
print(out["Payload"].read().decode())
# 3. Ship new code, then clean up.
lam.update_function_code(FunctionName="hello", ZipFile=zip_handler(
"def handler(event, ctx):\n return {'greeting': 'updated'}\n"
))
lam.delete_function(FunctionName="hello")// --- TypeScript (AWS SDK v3) ---
import {
LambdaClient, CreateFunctionCommand, InvokeCommand,
UpdateFunctionCodeCommand, DeleteFunctionCommand, waitUntilFunctionActiveV2,
} from "@aws-sdk/client-lambda";
import AdmZip from "adm-zip";
const lam = new LambdaClient({ region: "us-east-1" });
function zipHandler(source: string): Uint8Array {
const zip = new AdmZip();
zip.addFile("index.js", Buffer.from(source));
return zip.toBuffer();
}
// 1. Create with a zipped package and an existing execution role ARN.
await lam.send(new CreateFunctionCommand({
FunctionName: "hello",
Runtime: "nodejs20.x",
Role: "arn:aws:iam::111122223333:role/lambda-basic-exec",
Handler: "index.handler",
Code: { ZipFile: zipHandler(
"exports.handler = async (event) => ({ greeting: `hi ${event.name ?? 'world'}` });"
) },
}));
// 2. Wait until the function is active, then invoke it.
await waitUntilFunctionActiveV2({ client: lam, maxWaitTime: 120 }, { FunctionName: "hello" });
const out = await lam.send(new InvokeCommand({
FunctionName: "hello", Payload: JSON.stringify({ name: "Ada" }),
}));
console.log(new TextDecoder().decode(out.Payload));
// 3. Ship new code, then clean up.
await lam.send(new UpdateFunctionCodeCommand({
FunctionName: "hello",
ZipFile: zipHandler("exports.handler = async () => ({ greeting: 'updated' });"),
}));
await lam.send(new DeleteFunctionCommand({ FunctionName: "hello" }));What this demonstrates:
CreateFunction needs four essentials: runtime, handler, an execution role ARN, and code.Pending, so wait on the active waiter before invoking.UpdateFunctionCode changes code on the existing function without recreating it.AWSLambdaBasicExecutionRole for CloudWatch Logs.file.function - index.handler means the handler export in index.py/index.js.python3.12, nodejs20.x) that executes your code.Pending.Invoke defaults to the RequestResponse type (synchronous); pass InvocationType="Event" to fire and forget.A successful invoke can still contain a function-level error. Check for it rather than assuming success.
# --- Python (boto3) ---
out = lam.invoke(FunctionName="hello", Payload=b"{}")
if out.get("FunctionError"):
print("function threw:", out["Payload"].read().decode())
else:
print("ok:", out["Payload"].read().decode())// --- TypeScript (AWS SDK v3) ---
const out = await lam.send(new InvokeCommand({ FunctionName: "hello", Payload: "{}" }));
const body = new TextDecoder().decode(out.Payload);
if (out.FunctionError) console.log("function threw:", body);
else console.log("ok:", body);The HTTP call succeeds (status 200) even when your handler throws, so always inspect FunctionError.
For fire-and-forget work, set the invocation type to Event. Lambda queues the call and returns 202 immediately, and failures route to a dead-letter queue or on-failure destination if configured.
Pending and rejects invokes. Fix: wait on function_active_v2 after create or update.Handler must match the file and exported function names exactly. Fix: align index.handler with your file (index.py/index.js) and export.FunctionError on the response, not just the status code.ZipFile inline package is capped; larger code must come from S3. Fix: upload to S3 and pass Code={"S3Bucket": ..., "S3Key": ...}.UpdateFunctionCode and UpdateFunctionConfiguration on the existing function.| Alternative | Use When | Don't Use When |
|---|---|---|
| Lambda via SDK (this page) | Programmatic create/invoke/update from code | Managing a function's own source across a team |
| SAM / CDK / Serverless Framework | Deploying and versioning functions as infrastructure | One-off imperative invokes |
| Container image functions | Large dependencies or custom runtimes | Small handlers a zip covers |
| Direct invoke via API Gateway / URL | Exposing the function over HTTP to clients | Server-to-server calls that can use Invoke |
| Step Functions | Orchestrating many functions with retries and state | A single standalone function |
A function name, a runtime, a handler string, an execution role ARN, and a code package (an inline zip or an S3 reference). Everything else has defaults.
It is the IAM role Lambda assumes while running your function. Its permissions decide what the function's own SDK calls can do, and it needs log permissions to write to CloudWatch.
It is probably still Pending while Lambda processes the package. Wait on the function_active_v2 waiter after create or update before invoking.
Check the FunctionError field on the invoke response. The HTTP call returns 200 even when your code throws, so the status code alone is not enough.
The default RequestResponse type runs the function and returns its output. Set InvocationType="Event" for fire-and-forget, where Lambda queues the call and returns immediately.
Call UpdateFunctionCode on the existing function. Lambda swaps the package and keeps the same ARN and configuration, so callers are unaffected.
Yes. Any zip bytes work as the ZipFile package. The examples build the zip in memory, but reading a prebuilt zip from disk is equally valid.
The inline ZipFile has a size limit. Upload the zip to S3 and pass Code with S3Bucket and S3Key, or use a container image for very large dependencies.
Set environment variables via Environment on create, or UpdateFunctionConfiguration later. The handler reads them like any process environment variable.
For a function's own source and config, prefer a framework or IaC (SAM, CDK, Serverless) so deploys are versioned and repeatable. Use raw SDK calls for invoking and for tooling.
Stack versions: This page was written for boto3 1.43.x (Python 3.10+) and the AWS SDK for JavaScript v3 (Node.js 18+).
Revisado por Chris St. John·Última actualización: 24 jul 2026