Skip to content

Commit 08adcdb

Browse files
committed
New pattern - REST API Hello World (.NET)
1 parent be903e3 commit 08adcdb

File tree

8 files changed

+367
-0
lines changed

8 files changed

+367
-0
lines changed
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
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+
- src - 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+
* .NET Core - [Install .NET Core](https://www.microsoft.com/net/download)
34+
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)
35+
36+
To build and deploy your application for the first time, run the following in your shell:
37+
38+
```bash
39+
sam build
40+
sam deploy --guided
41+
```
42+
43+
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:
44+
45+
* **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.
46+
* **AWS Region**: The AWS region you want to deploy your app to.
47+
* **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.
48+
* **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.
49+
* **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.
50+
51+
You can find your API Gateway Endpoint URL in the output values displayed after deployment.
52+
53+
## Use the SAM CLI to build and test locally
54+
55+
Build your application with the `sam build` command.
56+
57+
```bash
58+
$ sam build
59+
```
60+
61+
The SAM CLI installs dependencies defined in `src/HelloWorld.csproj`, creates a deployment package, and saves it in the `.aws-sam/build` folder.
62+
63+
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.
64+
65+
Run functions locally and invoke them with the `sam local invoke` command.
66+
67+
```bash
68+
$ sam local invoke HelloWorldFunction --event events/event.json
69+
```
70+
71+
The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.
72+
73+
```bash
74+
$ sam local start-api
75+
$ curl http://localhost:3000/
76+
```
77+
78+
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.
79+
80+
```yaml
81+
Events:
82+
HelloWorld:
83+
Type: Api
84+
Properties:
85+
Path: /hello
86+
Method: get
87+
```
88+
89+
## Add a resource to your application
90+
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.
91+
92+
## Fetch, tail, and filter Lambda function logs
93+
94+
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.
95+
96+
`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.
97+
98+
```bash
99+
$ sam logs -n HelloWorldFunction --stack-name YOUR-STACK-NAME --tail
100+
```
101+
102+
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).
103+
104+
105+
## Cleanup
106+
107+
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:
108+
109+
```bash
110+
sam delete --stack-name YOUR-STACK-NAME
111+
```
112+
113+
## Resources
114+
115+
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.
116+
117+
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": ".NET",
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-dotnet",
17+
"templateURL": "serverless-patterns/apig-rest-api-lambda-dotnet",
18+
"projectFolder": "apig-rest-api-lambda-dotnet",
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: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"fileOptions": {
3+
"excludeSearchPatterns": [
4+
"**/bin/**/*",
5+
"**/obj/**/*"
6+
]
7+
}
8+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
3+
using System.Threading.Tasks;
4+
using System.Net.Http;
5+
using System.Text.Json;
6+
7+
using Amazon.Lambda.Core;
8+
using Amazon.Lambda.APIGatewayEvents;
9+
10+
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
11+
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
12+
13+
namespace HelloWorld;
14+
15+
public class Function
16+
{
17+
18+
private static readonly HttpClient client = new HttpClient();
19+
20+
private static async Task<string> GetCallingIP()
21+
{
22+
client.DefaultRequestHeaders.Accept.Clear();
23+
client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");
24+
25+
var msg = await client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false);
26+
27+
return msg.Replace("\n","");
28+
}
29+
30+
public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
31+
{
32+
33+
var location = await GetCallingIP();
34+
var body = new Dictionary<string, string>
35+
{
36+
{ "message", "hello world" },
37+
{ "location", location }
38+
};
39+
40+
return new APIGatewayProxyResponse
41+
{
42+
Body = JsonSerializer.Serialize(body),
43+
StatusCode = 200,
44+
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
45+
};
46+
}
47+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
<PropertyGroup>
3+
<TargetFramework>net8.0</TargetFramework>
4+
<ImplicitUsings>enable</ImplicitUsings>
5+
<Nullable>enable</Nullable>
6+
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
7+
<AWSProjectType>Lambda</AWSProjectType>
8+
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
9+
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
10+
<!-- Generate ready to run images during publishing to improve cold start time. -->
11+
<PublishReadyToRun>true</PublishReadyToRun>
12+
</PropertyGroup>
13+
<ItemGroup>
14+
<PackageReference Include="Amazon.Lambda.Core" Version="2.2.0" />
15+
<PackageReference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.4.0" />
16+
<PackageReference Include="Amazon.Lambda.APIGatewayEvents" Version="2.7.0" />
17+
</ItemGroup>
18+
</Project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"Information": [
3+
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
4+
"To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
5+
"dotnet lambda help",
6+
"All the command line options for the Lambda command can be specified in this file."
7+
],
8+
"profile": "",
9+
"region": "",
10+
"configuration": "Release",
11+
"template": "template.yaml"
12+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
AWSTemplateFormatVersion: '2010-09-09'
2+
Transform: AWS::Serverless-2016-10-31
3+
Description: >
4+
Sample SAM Template for REST API Lambda Hello World
5+
6+
# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
7+
Globals:
8+
Function:
9+
Timeout: 10
10+
MemorySize: 512
11+
12+
Resources:
13+
HelloWorldFunction:
14+
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
15+
Properties:
16+
CodeUri: ./src/HelloWorld/
17+
Handler: HelloWorld::HelloWorld.Function::FunctionHandler
18+
Runtime: dotnet8
19+
Architectures:
20+
- x86_64
21+
MemorySize: 512
22+
Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object
23+
Variables:
24+
PARAM1: VALUE
25+
Events:
26+
HelloWorld:
27+
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
28+
Properties:
29+
Path: /hello
30+
Method: get
31+
32+
Outputs:
33+
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
34+
# Find out more about other implicit resources you can reference within SAM
35+
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
36+
HelloWorldApi:
37+
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
38+
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
39+
HelloWorldFunction:
40+
Description: "Hello World Lambda Function ARN"
41+
Value: !GetAtt HelloWorldFunction.Arn
42+
HelloWorldFunctionIamRole:
43+
Description: "Implicit IAM Role created for Hello World function"
44+
Value: !GetAtt HelloWorldFunctionRole.Arn

0 commit comments

Comments
 (0)