Skip to content

Commit 1559702

Browse files
committed
New pattern - REST API hello world (java)
1 parent be903e3 commit 1559702

File tree

6 files changed

+384
-0
lines changed

6 files changed

+384
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package helloworld;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.net.URL;
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
import java.util.stream.Collectors;
10+
11+
import com.amazonaws.services.lambda.runtime.Context;
12+
import com.amazonaws.services.lambda.runtime.RequestHandler;
13+
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
14+
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
15+
16+
/**
17+
* Handler for requests to Lambda function.
18+
*/
19+
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
20+
21+
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
22+
Map<String, String> headers = new HashMap<>();
23+
headers.put("Content-Type", "application/json");
24+
headers.put("X-Custom-Header", "application/json");
25+
26+
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
27+
.withHeaders(headers);
28+
try {
29+
final String pageContents = this.getPageContents("https://checkip.amazonaws.com");
30+
String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents);
31+
32+
return response
33+
.withStatusCode(200)
34+
.withBody(output);
35+
} catch (IOException e) {
36+
return response
37+
.withBody("{}")
38+
.withStatusCode(500);
39+
}
40+
}
41+
42+
private String getPageContents(String address) throws IOException{
43+
URL url = new URL(address);
44+
try(BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
45+
return br.lines().collect(Collectors.joining(System.lineSeparator()));
46+
}
47+
}
48+
}
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>helloworld</groupId>
5+
<artifactId>HelloWorld</artifactId>
6+
<version>1.0</version>
7+
<packaging>jar</packaging>
8+
<name>A sample Hello World created for SAM CLI.</name>
9+
<properties>
10+
<maven.compiler.source>21</maven.compiler.source>
11+
<maven.compiler.target>21</maven.compiler.target>
12+
</properties>
13+
14+
<dependencies>
15+
<dependency>
16+
<groupId>com.amazonaws</groupId>
17+
<artifactId>aws-lambda-java-core</artifactId>
18+
<version>1.2.2</version>
19+
</dependency>
20+
<dependency>
21+
<groupId>com.amazonaws</groupId>
22+
<artifactId>aws-lambda-java-events</artifactId>
23+
<version>3.11.0</version>
24+
</dependency>
25+
<dependency>
26+
<groupId>junit</groupId>
27+
<artifactId>junit</artifactId>
28+
<version>4.13.2</version>
29+
<scope>test</scope>
30+
</dependency>
31+
</dependencies>
32+
33+
<build>
34+
<plugins>
35+
<plugin>
36+
<groupId>org.apache.maven.plugins</groupId>
37+
<artifactId>maven-shade-plugin</artifactId>
38+
<version>3.2.4</version>
39+
<configuration>
40+
</configuration>
41+
<executions>
42+
<execution>
43+
<phase>package</phase>
44+
<goals>
45+
<goal>shade</goal>
46+
</goals>
47+
</execution>
48+
</executions>
49+
</plugin>
50+
</plugins>
51+
</build>
52+
</project>
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
# Hello World AWS Lambda and Amazon API Gateway REST API
2+
3+
This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
4+
5+
- HelloWorldFunction/src/main - Code for the application's Lambda function.
6+
- events - Invocation events that you can use to invoke the function.
7+
- template.yaml - A template that defines the application's AWS resources.
8+
9+
The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.
10+
11+
If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
12+
The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.
13+
14+
* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
15+
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
16+
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
17+
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
18+
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
19+
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
20+
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
21+
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
22+
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
23+
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
24+
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)
25+
26+
## Deploy the sample application
27+
28+
The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
29+
30+
To use the SAM CLI, you need the following tools.
31+
32+
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
33+
* java21 - [Install the Java 21](https://docs.aws.amazon.com/corretto/latest/corretto-21-ug/downloads-list.html)
34+
* Maven - [Install Maven](https://maven.apache.org/install.html)
35+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
36+
37+
To build and deploy your application for the first time, run the following in your shell:
38+
39+
```bash
40+
sam build
41+
sam deploy --guided
42+
```
43+
44+
The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:
45+
46+
* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
47+
* **AWS Region**: The AWS region you want to deploy your app to.
48+
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
49+
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
50+
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.
51+
52+
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
53+
54+
## Use the SAM CLI to build and test locally
55+
56+
Build your application with the `sam build` command.
57+
58+
```bash
59+
$ sam build
60+
```
61+
62+
The SAM CLI installs dependencies defined in `HelloWorldFunction/pom.xml`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
63+
64+
Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.
65+
66+
Run functions locally and invoke them with the `sam local invoke` command.
67+
68+
```bash
69+
$ sam local invoke HelloWorldFunction --event events/event.json
70+
```
71+
72+
The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
73+
74+
```bash
75+
$ sam local start-api
76+
$ curl http://localhost:3000/
77+
```
78+
79+
The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.
80+
81+
```yaml
82+
Events:
83+
HelloWorld:
84+
Type: Api
85+
Properties:
86+
Path: /hello
87+
Method: get
88+
```
89+
90+
## Add a resource to your application
91+
The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
92+
93+
## Fetch, tail, and filter Lambda function logs
94+
95+
To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.
96+
97+
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
98+
99+
```bash
100+
$ sam logs -n HelloWorldFunction --stack-name YOUR_STACK_NAME --tail
101+
```
102+
103+
You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).
104+
105+
106+
## Cleanup
107+
108+
To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
109+
110+
```bash
111+
sam delete --stack-name YOUR_STACK_NAME
112+
```
113+
114+
## Resources
115+
116+
See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.
117+
118+
Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
{
2+
"body": "{\"message\": \"hello world\"}",
3+
"resource": "/{proxy+}",
4+
"path": "/path/to/resource",
5+
"httpMethod": "POST",
6+
"isBase64Encoded": false,
7+
"queryStringParameters": {
8+
"foo": "bar"
9+
},
10+
"pathParameters": {
11+
"proxy": "/path/to/resource"
12+
},
13+
"stageVariables": {
14+
"baz": "qux"
15+
},
16+
"headers": {
17+
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
18+
"Accept-Encoding": "gzip, deflate, sdch",
19+
"Accept-Language": "en-US,en;q=0.8",
20+
"Cache-Control": "max-age=0",
21+
"CloudFront-Forwarded-Proto": "https",
22+
"CloudFront-Is-Desktop-Viewer": "true",
23+
"CloudFront-Is-Mobile-Viewer": "false",
24+
"CloudFront-Is-SmartTV-Viewer": "false",
25+
"CloudFront-Is-Tablet-Viewer": "false",
26+
"CloudFront-Viewer-Country": "US",
27+
"Host": "1234567890.execute-api.us-east-1.amazonaws.com",
28+
"Upgrade-Insecure-Requests": "1",
29+
"User-Agent": "Custom User Agent String",
30+
"Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
31+
"X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==",
32+
"X-Forwarded-For": "127.0.0.1, 127.0.0.2",
33+
"X-Forwarded-Port": "443",
34+
"X-Forwarded-Proto": "https"
35+
},
36+
"requestContext": {
37+
"accountId": "123456789012",
38+
"resourceId": "123456",
39+
"stage": "prod",
40+
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef",
41+
"requestTime": "09/Apr/2015:12:34:56 +0000",
42+
"requestTimeEpoch": 1428582896000,
43+
"identity": {
44+
"cognitoIdentityPoolId": null,
45+
"accountId": null,
46+
"cognitoIdentityId": null,
47+
"caller": null,
48+
"accessKey": null,
49+
"sourceIp": "127.0.0.1",
50+
"cognitoAuthenticationType": null,
51+
"cognitoAuthenticationProvider": null,
52+
"userArn": null,
53+
"userAgent": "Custom User Agent String",
54+
"user": null
55+
},
56+
"path": "/prod/path/to/resource",
57+
"resourcePath": "/{proxy+}",
58+
"httpMethod": "POST",
59+
"apiId": "1234567890",
60+
"protocol": "HTTP/1.1"
61+
}
62+
}
63+
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
{
2+
"title": "Hello World AWS Lambda and Amazon API Gateway REST API",
3+
"description": "Create a simple Lambda Function connected to a REST API.",
4+
"language": "Java",
5+
"level": "200",
6+
"framework": "SAM",
7+
"introBox": {
8+
"headline": "How it works",
9+
"text": [
10+
"This sample project demonstrates how to trigger a simple Lambda function using a REST API.",
11+
"This pattern deploys one Lambda Function, andn one API Gateway REST API."
12+
]
13+
},
14+
"gitHub": {
15+
"template": {
16+
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apig-rest-api-lambda-java",
17+
"templateURL": "serverless-patterns/apig-rest-api-lambda-java",
18+
"projectFolder": "apig-rest-api-lambda-java",
19+
"templateFile": "template.yaml"
20+
}
21+
},
22+
"resources": {
23+
"bullets": [
24+
{
25+
"text": "Trigger Lambda with a REST API",
26+
"link": "https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html"
27+
},
28+
{
29+
"text": "Amazon API Gateway REST API",
30+
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-rest-api.html"
31+
}
32+
]
33+
},
34+
"deploy": {
35+
"text": [
36+
"sam deploy --guided"
37+
]
38+
},
39+
"testing": {
40+
"text": [
41+
"See the GitHub repo for detailed testing instructions."
42+
]
43+
},
44+
"cleanup": {
45+
"text": [
46+
"Delete the application: <code>sam delete</code>."
47+
]
48+
},
49+
"authors": [
50+
{
51+
"name": "Your name",
52+
"image": "link-to-your-photo.jpg",
53+
"bio": "Your bio.",
54+
"linkedin": "linked-in-ID",
55+
"twitter": "twitter-handle"
56+
}
57+
]
58+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: >
4+
REST API Lambda Hello World
5+
6+
Sample SAM Template for REST API Lambda Hello World
7+
8+
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
9+
Globals:
10+
Function:
11+
Timeout: 20
12+
MemorySize: 512
13+
14+
Resources:
15+
HelloWorldFunction:
16+
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
17+
Properties:
18+
CodeUri: HelloWorldFunction
19+
Handler: helloworld.App::handleRequest
20+
Runtime: java21
21+
Architectures:
22+
- x86_64
23+
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
24+
Variables:
25+
PARAM1: VALUE
26+
Events:
27+
HelloWorld:
28+
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
29+
Properties:
30+
Path: /hello
31+
Method: get
32+
33+
Outputs:
34+
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
35+
# Find out more about other implicit resources you can reference within SAM
36+
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
37+
HelloWorldApi:
38+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
39+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
40+
HelloWorldFunction:
41+
Description: "Hello World Lambda Function ARN"
42+
Value: !GetAtt HelloWorldFunction.Arn
43+
HelloWorldFunctionIamRole:
44+
Description: "Implicit IAM Role created for Hello World function"
45+
Value: !GetAtt HelloWorldFunctionRole.Arn

0 commit comments

Comments
 (0)