Definición de recursos serverless
Escriba plantillas de SAM para definir funciones de Lambda, endpoints de API Gateway, tablas de DynamoDB y otros componentes serverless.
Definición de recursos serverless es una lección gratuita de Serverless Backend with AWS Lambda & API Gateway en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Serverless Backend with AWS Lambda & API Gateway, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What are SAM Templates?
AWS Serverless Application Model (SAM) templates are a powerful way to define your serverless applications using Infrastructure as Code (IaC).
Instead of manually configuring resources in the AWS console, you describe them in a YAML or JSON file. This makes your deployments repeatable, version-controlled, and easier to manage.
Anatomy of a SAM Template
A SAM template has a clear structure. The most important parts are:
AWSTemplateFormatVersion: Specifies the template format version.Transform: AlwaysAWS::Serverless-2016-10-31for SAM.Description: A brief description of your application.Resources: Where you define all your AWS components.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: My First SAM App
Resources:
# Your serverless resources go hereDefining a Serverless Function
The core of many serverless applications is the AWS Lambda function. In SAM, you declare a Lambda using the AWS::Serverless::Function resource type.
You need to specify its handler, runtime, and where its code is located.
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: s3://my-bucket/my-app.zip
MemorySize: 128
Timeout: 30Key Lambda Properties
Let's break down some common AWS::Serverless::Function properties:
Handler: The entry point in your code (e.g.,filename.function_name).Runtime: The programming language runtime (e.g.,python3.9,nodejs18.x).CodeUri: Path to your function's deployment package (local or S3).MemorySize: RAM allocated to the function (MB).Timeout: Max execution time (seconds).
API Gateway as an Event Source
To make your Lambda function accessible via an HTTP endpoint, you integrate it with Amazon API Gateway. In SAM, you do this by adding an Events property to your function.
The HttpApi type is often preferred for its simplicity and cost-effectiveness.
Resources:
MyApiFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: s3://my-bucket/api-app.zip
Events:
MyApiEvent:
Type: HttpApi
Properties:
Path: /hello
Method: GETDefining a DynamoDB Table
For data persistence, you can define a DynamoDB table directly in your SAM template. SAM provides a convenient AWS::Serverless::SimpleTable resource type.
This creates a basic DynamoDB table with a primary key. For more advanced configurations, you can use AWS::DynamoDB::Table.
Resources:
MyDataTable:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1IAM Permissions for Resources
Your Lambda functions often need permission to interact with other AWS services, like DynamoDB. You grant these permissions using IAM (Identity and Access Management) policies.
SAM allows you to attach policies directly to your Lambda function's execution role using the Policies property.
Resources:
MyLambdaWithDbAccess:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: s3://my-bucket/db-app.zip
Policies:
- DynamoDBReadWriteAccess:
TableName: !Ref MyDataTable # Grants access to MyDataTable
Events:
MyApiEvent:
Type: HttpApi
Properties:
Path: /items
Method: GET
MyDataTable:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: id
Type: StringExporting Important Values
After deploying your serverless application, you often need to know the endpoint URL of your API or the name of your DynamoDB table.
The Outputs section in your SAM template allows you to export these values, making them easily accessible after deployment.
Outputs:
ApiUrl:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/hello"A Full Serverless Template
Here's a more complete SAM template that defines an HTTP API endpoint, a Lambda function to handle requests, and a DynamoDB table for data storage.
Notice how different resource types are declared and linked together.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: A complete serverless API with Lambda and DynamoDB
Resources:
MyApiFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.lambda_handler
Runtime: python3.9
CodeUri: s3://my-bucket/full-app.zip
Policies:
- DynamoDBReadWriteAccess:
TableName: !Ref MyItemsTable
Events:
MyApiEvent:
Type: HttpApi
Properties:
Path: /items
Method: GET
MyItemsTable:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: itemId
Type: String
Outputs:
ApiEndpoint:
Description: "API Gateway endpoint URL"
Value: !Sub "https://${ServerlessHttpApi}.execute-api.${AWS::Region}.amazonaws.com/items"SAM Template Check
Which of the following are valid top-level sections in a SAM template?
Recap: Defining Serverless Resources
In this lesson, you learned how to define various serverless resources within a SAM template. We covered:
- The basic structure of a SAM template.
- Declaring
AWS::Serverless::Functionfor Lambda. - Integrating Lambda with API Gateway using
Events. - Defining
AWS::Serverless::SimpleTablefor DynamoDB. - Granting permissions with IAM
Policies. - Using the
Outputssection to export values.
Next, we'll learn how to deploy these templates to AWS!
Preguntas frecuentes
¿La lección «Definición de recursos serverless» es gratis?
Sí — el texto completo de «Definición de recursos serverless» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Serverless Backend with AWS Lambda & API Gateway, actualiza a CoddyKit PRO. El curso de Serverless Backend with AWS Lambda & API Gateway incluye 4 lecciones en total.
¿Qué aprenderé en «Definición de recursos serverless»?
Escriba plantillas de SAM para definir funciones de Lambda, endpoints de API Gateway, tablas de DynamoDB y otros componentes serverless. Practicas Serverless Backend with AWS Lambda & API Gateway con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Serverless Backend with AWS Lambda & API Gateway?
No se requiere experiencia previa. Serverless Backend with AWS Lambda & API Gateway en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Definición de recursos serverless»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Serverless Backend with AWS Lambda & API Gateway?
Sí. Cada lección de Serverless Backend with AWS Lambda & API Gateway incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Introducción a AWS SAM
- Definición de recursos serverless
- Implementación de aplicaciones SAM
- Pruebas y depuración locales con SAM CLI