Primeira função Lambda (Python)
Escreva e implante sua primeira função do AWS Lambda usando Python, aprendendo sua estrutura básica e seu modelo de execução.
Primeira função Lambda (Python) é uma aula grátis de Serverless Backend with AWS Lambda & API Gateway no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Serverless Backend with AWS Lambda & API Gateway, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Welcome to AWS Lambda!
Time for your first function. AWS Lambda is Function as a Service: upload code, and Lambda runs it with zero servers to provision.
Why Python for Lambda?
Python is a great Lambda runtime — readable, rich libraries, perfect for APIs, data processing, and automation. Beginner-friendly too.
The Lambda Handler Function
Every Lambda needs an entry point: the handler. Lambda calls it with two args — event (input data) and context (runtime info).
Your First Python Lambda
Here's a minimal "Hello World" Lambda. All your logic lives in lambda_handler — run it locally to feel the shape.
import json
def lambda_handler(event, context):
# Your function's logic goes here
message = "Hello from your first Lambda!"
# Lambda functions typically return a dictionary
return {
'statusCode': 200,
'body': json.dumps(message)
}
# This block allows you to test your function locally
if __name__ == "__main__":
# Simulate an empty event and context for a simple test
mock_event = {}
mock_context = None
response = lambda_handler(mock_event, mock_context)
print("Local Test Response:", response)Understanding the 'event'
The event parameter carries the input that triggered your function, delivered as JSON and converted into a Python dict — an API call, an S3 upload, a queue message.
Code: Reading from the Event
Now read a name from the event, falling back to a default. Notice event.get('key', default) for safe access without KeyErrors.
import json
def lambda_handler(event, context):
# Get 'name' from the event, or default to 'there'
name = event.get('name', 'there')
message = f"Hello, {name} from Lambda!"
return {
'statusCode': 200,
'body': json.dumps(message)
}
# Local testing with different events
if __name__ == "__main__":
mock_event_with_name = {"name": "CoddyKit User"}
response_with_name = lambda_handler(mock_event_with_name, None)
print("With name:", response_with_name)
mock_event_no_name = {}
response_no_name = lambda_handler(mock_event_no_name, None)
print("Without name:", response_no_name)The 'context' Object
The context object exposes runtime info like aws_request_id, function_name, and remaining execution time. Handy even if you skip it often.
Returning a Standard Response
When API Gateway triggers your function, it expects a specific shape: a statusCode and a body that's a JSON string. That's how the client gets a clean response.
Code: Complete API Response
Here's a fuller, API-ready response with a Content-Type header and structured JSON body. We fake a context for local testing.
import json
def lambda_handler(event, context):
name = event.get('name', 'World')
# Simulate a context object for local testing
request_id = getattr(context, 'aws_request_id', 'local-test-id')
response_message = f"Greetings, {name}! Your request ID is {request_id}."
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json'
},
'body': json.dumps({
'message': response_message,
'input_data': event # Echoing input for demonstration
})
}
# Local testing with a dummy context
if __name__ == "__main__":
class MockContext:
aws_request_id = 'mock-request-123'
mock_event = {"name": "CoddyKit"}
mock_context_obj = MockContext()
response = lambda_handler(mock_event, mock_context_obj)
print("Full API Response:", response)How Lambda Executes Your Code
On each event, Lambda spins up (or reuses) a container, loads your code, calls the handler, runs it, and returns the result — then waits or shuts down.
Quick Check
Which of the following best describes the purpose of the event parameter in a Python Lambda handler function?
Recap: Your First Lambda!
Recap: Lambda runs code with no servers. The handler is your entry point, event carries input as a dict, context gives runtime info, and you return a status + JSON body.
Perguntas Frequentes
A aula “Primeira função Lambda (Python)” é grátis?
Sim — o texto completo de “Primeira função Lambda (Python)” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Serverless Backend with AWS Lambda & API Gateway, atualize para CoddyKit PRO. O curso de Serverless Backend with AWS Lambda & API Gateway inclui 4 aulas no total.
O que vou aprender em “Primeira função Lambda (Python)”?
Escreva e implante sua primeira função do AWS Lambda usando Python, aprendendo sua estrutura básica e seu modelo de execução. Você pratica Serverless Backend with AWS Lambda & API Gateway com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Serverless Backend with AWS Lambda & API Gateway?
Nenhuma experiência prévia é necessária. Serverless Backend with AWS Lambda & API Gateway no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Primeira função Lambda (Python)”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Serverless Backend with AWS Lambda & API Gateway?
Sim. Cada aula de Serverless Backend with AWS Lambda & API Gateway inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O que é arquitetura sem servidor?
- Visão geral dos principais serviços da AWS
- Primeira função Lambda (Python)
- Entendendo o modelo de execução sem servidor