En mi artículo anterior, hablé sobre cómo AWS Chalice lo ayuda a crear rápidamente una aplicación sin servidor basada en Python e implementarla en AWS en unos pocos minutos.
Si bien fue un prototipo rápido y divertido, Python puede no ser el lenguaje elegido por muchos cuando se trata de ejecutar aplicaciones de producción a gran escala.
Muchas organizaciones utilizan Java como su lenguaje de desarrollo principal, y muchos desarrolladores también se están moviendo hacia lenguajes más nuevos como Go.
En este artículo, lo guiaré a través de los pasos necesarios para crear e implementar la misma aplicación sin servidor que recibe las últimas noticias de Google News. Pero esta vez, usaremos AWS Serverless Application Model (SAM) y Java para nuestro desarrollo.
Al igual que Chalice, la AWS SAM CLI ofrece un amplio conjunto de herramientas que permiten a los desarrolladores crear aplicaciones sin servidor rápidamente.
Prerrequisitos
Este tutorial requiere una cuenta de AWS. Si aún no tiene uno, siga adelante y cree uno. Nuestra aplicación utilizará solo los recursos de nivel gratuito, por lo que el costo no debería ser un problema.
También necesita configurar la seguridad y crear usuarios y roles para su acceso.
Cómo configurar las credenciales de AWS
SAM utiliza la AWS Command Line Interface (CLI) en segundo plano para implementar el proyecto. Si no ha utilizado la CLI de AWS antes para trabajar con recursos de AWS, puede instalarla siguiendo las pautas aquí.
Una vez instalado, debe configurar su AWS CLI para usar las credenciales de su cuenta de AWS.

Cómo instalar SAM
A continuación, debe instalar SAM. Usaremos Java en este tutorial, pero puede usar cualquier tiempo de ejecución de lenguaje compatible con AWS Lambda.
Verificar la instalación de Java
$ java --version openjdk 11.0.8 2020-07-14 OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.8+10) OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.8+10, mixed mode)
Instalar SAM CLI
Dependiendo de su sistema operativo, las instrucciones de instalación para SAM CLI variarán. Este artículo cubre las instrucciones para instalarlo en MacOS.
El enfoque recomendado para instalar SAM CLI en macOS es utilizar el administrador de paquetes Homebrew.
Verifique que tenga Homebrew instalado, así:
$ brew --version Homebrew/homebrew-core (git revision fe68a; last commit 2020-10-15) Homebrew/homebrew-cask (git revision 4a2c25; last commit 2020-10-15)
De lo contrario, puede instalar Homebrew usando el siguiente comando:
$ /bin/bash -c "$(curl -fsSL //raw.githubusercontent.com/Homebrew/install/master/install.sh)"
A continuación, instale SAM usando el siguiente comando:
brew tap aws/tap brew install aws-sam-cli
Verificar la instalación de SAM
$ sam --version SAM CLI, version 1.6.2
Cómo crear un proyecto
A continuación, ejecute el sam-init
comando para crear un nuevo proyecto.
sam init -r java11 -d maven --app-template hello-world -n daily-news-java
De forma predeterminada, SAM crea un proyecto de Python. Dado que queremos crear un proyecto Java, necesitaremos pasar algunos parámetros adicionales.
Parámetros:
-r java11
: use el tiempo de ejecución de Java 11-d maven
: use maven como administrador de dependencias--app-template hello-world
: use la plantilla de inicio rápido HelloWorld-n daily-news-java
: el nombre de nuestro proyecto
Esto creará una daily-news-java
carpeta en su directorio actual. Puede ver que SAM ha creado varios archivos en esta carpeta.

Echemos un vistazo al App.java
archivo.
El sam-init
comando creó una función Lambda simple que devuelve el cuerpo JSON {"message": "hello world"}
y la dirección IP de la máquina cuando se llama. Ahora podemos cambiar esta plantilla y agregar más código para leer noticias de Google.
Ahora echemos un vistazo al template.yml
archivo.
Contiene la plantilla de CloudFormation que crea nuestros recursos de Amazon API Gateway y AWS Lambda.
La configuración especifica Lambda que tenemos un HelloWorldFunction
lambda que se ejecuta en Java 11
y 512 MB
la memoria.
La configuración de la puerta de enlace API define un GET
método único con una /hello
ruta que usaremos para invocar la API.
Usaremos las bibliotecas de análisis XML y HTTP internas de Java, por lo que no es necesario que agreguemos ninguna dependencia a nuestro pom.xml
archivo.
Tenga en cuenta que el valor predeterminado pom.xml
proporcionado como parte del código repetitivo viene con el código fuente del compilador configurado en 1.8.
Necesitaremos actualizarlo para 11
que podamos usar la nueva biblioteca HTTP que es parte de Java 11.
Dado que Java está orientado a objetos, también creemos una NewsItem
clase que contenga el título y la fecha de publicación de una noticia.
Tenga en cuenta que hemos anulado el toString
método. Esto crea una representación JSON del objeto y evita el uso de bibliotecas de análisis JSON.
Next, you need to add a method to fetch the RSS feed from Google, parse it to extract the news title and publication date, and create a list of news items. To do this, add the following code to your App.java
:
Now let’s update the handleRequest
method in App.java
to invoke this method and return the list of news items as result.
Don’t forget to update the unit tests as well. They were written to test the presence of “hello world” in the response and will start failing after our change.
How to Start the Build
From the daily-news-java
folder, run the sam build
command.

This compiles your source code and builds any dependencies that you have in the application. It then moves all the files into the .aws-sam/build
folder so that they are ready to be packaged and deployed. It also updates the template.yml
file accordingly.
How to Test Your Application Locally
Now here’s the beautiful part about SAM. You can deploy and test your application locally! This is really helpful during the development stage when you want to test your code without having to deploy it to AWS.
The SAM CLI provides the sam local
command to run your application locally. This internally uses Docker to simulate the execution environment of Lambda. If you don’t have Docker installed, you can get it from here.
We can locally test our application in two ways:
- Hosting the API locally
- Directly invoking the Lambda function
Let’s take a look at both of these options.
Local Hosting
Use the following command to start the API locally:
sam local start-api
This internally creates a local server and exposes a local endpoint that replicates your REST API.

Once the Docker container is loaded, you can access the API on localhost
, like this:
curl //127.0.0.1:3000/hello
Direct Invocation
Use the following command to invoke the Lambda function:
sam local invoke "HelloWorldFunction" -e events/event.json

This directly invokes the Lambda function (just like we would call the main
method) and passes the event.json
file as payload.
How to Deploy the Project
Let’s deploy the application. From the daily-news-java
folder, run the sam deploy --guided
command. Follow the prompts and provide the required inputs (or just press Enter to accept the defaults).

This deploys our application on AWS using Amazon API Gateway and AWS Lambda. It takes the deployment artifacts that we built with the sam build
command, packages and uploads them to an Amazon S3 bucket created by the AWS SAM CLI, and deploys the application using AWS CloudFormation.



We can now try accessing the API using the endpoint URL provided above.

How to Clean Up Resources
We can use the aws cloudformation delete-stack
commandto delete the AWS CloudFormation stack along with all the resources it created when we ran the sam deploy
command.

Conclusion
Congratulations! You just deployed a serverless application on AWS using AWS SAM. It did involve a bit more work than earlier, but it wasn’t too hard either.
You can now go ahead and make any modifications to your App.java
file and rerun sam deploy
to redeploy your changes.
The full source code for this tutorial can be found here.
Thank you for staying with me so far. Hope you liked the article. You can connect with me on LinkedIn where I regularly discuss technology and life. Also take a look at some of my other articles on Medium.
Happy reading ?