Skip to content

docs: ASP.NET Core WebAPI example(s) #287

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Jun 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ deploy/**
.idea
.vscode
.vs/
.aws-sam

examples/SimpleLambda/.aws-sam
examples/SimpleLambda/samconfig.toml
Expand All @@ -20,4 +21,5 @@ AWS.Lambda.Powertools.sln.DotSettings.user
.DS_Store

dist/
site/
site/
samconfig.toml
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ We have provided examples focused specifically on each of the utilities. Each so
* **[Logging example](examples/Logging/)**
* **[Metrics example](examples/Metrics/)**
* **[Tracing example](examples/Tracing/)**
* **[Serverless API example](examples/ServerlessApi/)**

* **[Parameters example](examples/Parameters/)**
* **[Idempotency example](examples/Idempotency)**

Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ We have provided a few examples that should you how to use the each of the core
* [Tracing](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Tracing){target="_blank"}
* [Logging](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Logging/){target="_blank"}
* [Metrics](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Metrics/){target="_blank"}
* [Serverless API example](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/ServerlessApi/){target="_blank"}
* [Parameters](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Parameters/){target="_blank"}
* [Idempotency](https://github.com/aws-powertools/powertools-lambda-dotnet/tree/main/examples/Idempotency/){target="_blank"}

Expand Down
36 changes: 36 additions & 0 deletions examples/ServerlessApi/PowertoolsServerlessApiExample.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{97038683-80A8-4DEC-B494-E774D5D7CA8E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI", "src\LambdaPowertoolsAPI\LambdaPowertoolsAPI.csproj", "{07541883-22A3-49AB-9A7B-3E2C8CC347F5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{744F4880-67A3-4BC9-B4E7-D879EC646492}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LambdaPowertoolsAPI.Tests", "test\LambdaPowertoolsAPI.Tests\LambdaPowertoolsAPI.Tests.csproj", "{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07541883-22A3-49AB-9A7B-3E2C8CC347F5}.Release|Any CPU.Build.0 = Release|Any CPU
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{07541883-22A3-49AB-9A7B-3E2C8CC347F5} = {97038683-80A8-4DEC-B494-E774D5D7CA8E}
{151BBDCE-FB35-4025-A925-BEDD50DDCD9F} = {744F4880-67A3-4BC9-B4E7-D879EC646492}
EndGlobalSection
EndGlobal
243 changes: 243 additions & 0 deletions examples/ServerlessApi/Readme.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions examples/ServerlessApi/events/event.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"resource": "/{proxy+}",
"path": "api/values",
"httpMethod": "GET",
"body": "{\r\n\t\"message\": \"Hello\"\r\n}",
"isBase64Encoded": false,
"requestContext": {
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d"
}
}
10 changes: 10 additions & 0 deletions examples/ServerlessApi/events/event_getById.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"resource": "/{proxy+}",
"path": "api/values/5",
"httpMethod": "GET",
"body": "{\r\n\t\"message\": \"Hello\"\r\n}",
"isBase64Encoded": false,
"requestContext": {
"requestId": "4749a5a8-93ea-464e-8778-3bffc5f9a35d"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using Microsoft.AspNetCore.Mvc;
using System;
using AWS.Lambda.Powertools.Logging;
using AWS.Lambda.Powertools.Tracing;
using AWS.Lambda.Powertools.Metrics;

namespace LambdaPowertoolsAPI.Controllers;

[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
[Tracing(SegmentName = "Values::Get")]
public IEnumerable<string> Get()
{
Logger.LogInformation("Log entry information only about getting values? Or maybe something more ");

return new string[] { "value1", "value2" };
}

// GET api/values/5
[HttpGet("{id}")]
[Tracing(SegmentName = "Values::GetById")]
public string Get(int id)
{

try
{
Metrics.AddMetric("SuccessfulRetrieval", 1, MetricUnit.Count);
}
catch (Exception e)
{
Logger.LogError("Failed to add metric", e);
}
return "value";
}

// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
81 changes: 81 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/LambdaEntryPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization.SystemTextJson;
using AWS.Lambda.Powertools.Logging; // We are adding logging
using AWS.Lambda.Powertools.Tracing; // We are adding tracing
using AWS.Lambda.Powertools.Metrics; // We are adding metrics

namespace LambdaPowertoolsAPI;

/// <summary>
/// This class extends from APIGatewayProxyFunction which contains the method FunctionHandlerAsync which is the
/// actual Lambda function entry point. The Lambda handler field should be set to
///
/// LambdaPowertoolsAPI::LambdaPowertoolsAPI.LambdaEntryPoint::FunctionHandlerAsync
/// </summary>
public class LambdaEntryPoint :

// The base class must be set to match the AWS service invoking the Lambda function. If not Amazon.Lambda.AspNetCoreServer
// will fail to convert the incoming request correctly into a valid ASP.NET Core request.
//
// API Gateway REST API -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
// API Gateway HTTP API payload version 1.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
// API Gateway HTTP API payload version 2.0 -> Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction
// Application Load Balancer -> Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction
//
// Note: When using the AWS::Serverless::Function resource with an event type of "HttpApi" then payload version 2.0
// will be the default and you must make Amazon.Lambda.AspNetCoreServer.APIGatewayHttpApiV2ProxyFunction the base class.

Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
/// <summary>
/// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
/// needs to be configured in this method using the UseStartup<>() method.
/// </summary>
/// <param name="builder"></param>
protected override void Init(IWebHostBuilder builder)
{
builder
.UseStartup<Startup>();


Console.WriteLine("Startup done");
}


// We are defining some default dimensions.
private Dictionary<string, string> _defaultDimensions = new Dictionary<string, string>{
{"Environment", Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Unknown"},
{"Runtime",Environment.Version.ToString()}
};

[LambdaSerializer(typeof(DefaultLambdaJsonSerializer))]
[Logging(CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest, LogEvent = true)] // we are enabling logging, it needs to be added on method which have Lambda event
[Tracing] // Adding a tracing attribute here we will see additional function call which might be important in terms of debugging
[Metrics] // Metrics need to be initialized the best place is entry point in opposite on adding attribute on each controller.
public override Task<APIGatewayProxyResponse> FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext lambdaContext)
{

if (!_defaultDimensions.ContainsKey("Version"))
_defaultDimensions.Add("Version", lambdaContext.FunctionVersion ?? "Unknown");

// Setting the default dimensions. They will be added to every emitted metric.
Metrics.SetDefaultDimensions(_defaultDimensions);
return base.FunctionHandlerAsync(request, lambdaContext);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<AWSProjectType>Lambda</AWSProjectType>
<!-- This property makes the build directory similar to a publish directory and helps the AWS .NET Lambda Mock Test Tool find project dependencies. -->
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
<!-- Generate ready to run images during publishing to improve cold start time. -->
<PublishReadyToRun>true</PublishReadyToRun>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Amazon.Lambda.AspNetCoreServer" Version="8.1.0" />
<PackageReference Include="AWS.Lambda.Powertools.Logging" Version="1.1.0" />
<PackageReference Include="AWS.Lambda.Powertools.Metrics" Version="1.2.0" />
<PackageReference Include="AWS.Lambda.Powertools.Tracing" Version="1.1.0" />
</ItemGroup>
</Project>
34 changes: 34 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/LocalEntryPoint.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

namespace LambdaPowertoolsAPI;

/// <summary>
/// The Main function can be used to run the ASP.NET Core application locally using the Kestrel webserver.
/// </summary>
public class LocalEntryPoint
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
51 changes: 51 additions & 0 deletions examples/ServerlessApi/src/LambdaPowertoolsAPI/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

namespace LambdaPowertoolsAPI;

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseRouting();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"AWS": {
"Region": ""
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"Information": [
"This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
"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.",
"dotnet lambda help",
"All the command line options for the Lambda command can be specified in this file."
],
"profile": "",
"region": "",
"configuration": "Release",
"s3-prefix": "LambdaPowertoolsAPI/",
"template": "serverless.template",
"template-parameters": ""
}
Loading