Crear una función Lambda (desde consola)
- Ir a AWS Lambda
- Click en “Create function”
- Elegir:
- Author from scratch
- Nombre:
miLambdaAPI
- Runtime:
Python 3.12
(o el que prefieras) - Rol: crear uno nuevo con permisos básicos (
AWSLambdaBasicExecutionRole
)
Codigo de ejemplo
import json
def lambda_handler(event, context):
try:
body = json.loads(event.get('body', '{}'))
except json.JSONDecodeError:
return {
'statusCode': 400,
'body': 'Invalid JSON'
}
if 'age' not in body:
return {
'statusCode': 400,
'body': 'Missing age'
}
if body['age'] < 18:
return {
'statusCode': 400,
'body': 'Age must be greater than 18'
}
return {
'statusCode': 200,
'body': json.dumps({'message': 'OK', 'age': body['age']})
}
Crear una API REST con API Gateway (Lambda Proxy)
- Ir a API Gateway → “Create API”
- Elegir REST API (no “HTTP API”)
- Nombre:
miAPI
- Activar Lambda Proxy Integration
Crear un recurso y método
- En el panel izquierdo:
- Click en Actions → Create Resource
- Nombre:
/hello
- Seleccionar el recurso
/hello
→ Actions → Create Method → GET o POST - Seleccionar Lambda Function
- Marcar “Use Lambda Proxy integration” ✅
- Ingresar el nombre de tu Lambda (
miLambdaAPI
)
- Dar permisos cuando lo solicite
Deploy de la API
- Click en Actions → Deploy API
- Crear un nuevo Stage (ej:
test
) - Se obtendrá una URL como:
https://abc123.execute-api.us-east-1.amazonaws.com/test/hola
Probar con curl
curl -X POST https://abc123.execute-api.us-east-1.amazonaws.com/dev/hola \
-H "Content-Type: application/json" \
-d '{"age": 21}'
Respuesta esperada:
{
"message": "OK",
"age": 21
}
Dudas
¿Por qué aparece body
en el event
de Lambda?
API Gateway lo añade automáticamente cuando usas Lambda Proxy Integration. Transforma la petición HTTP en un objeto event
con esta estructura:
{
"resource": "/hola",
"path": "/hola",
"httpMethod": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": "{\"age\": 21}",
"isBase64Encoded": false
}
Entonces:
- El
body
es una cadena JSON, no un dict. - Necesitas usar
json.loads(event['body'])
para acceder a los datos reales.
Fuentes
- Documentación oficial de Lambda o pedir más ejemplos aquí.