aws-lambda-dotnet icon indicating copy to clipboard operation
aws-lambda-dotnet copied to clipboard

Lambda Annotations API Routing

Open jeastham1993 opened this issue 2 years ago • 2 comments

Describe the feature

With the release of the [LambdaGlobalProperties] attribute that can auto-generate the static Main() method for non managed and native AOT runtimes this functionality could be extended to provide API routing capabilities. The API annotations on methods could be used as part of a switch statement for the inbound API event.

Use Case

Running a simple web API on Lambda without needing to introduce the overhead of ASP.NET. Removes the need to set the ANNOTATIONS_HANDLER environment variable when running multiple API endpoints in the same Lambda function.

Allows the use of an API Gateway {proxy+} route with all API request routing to the same Lambda function.

Proposed Solution

The GenerateMain global properties attribute adds a switch statement based on an environment variable. Introduce a new ApiRouting Lambda Global Property that will generate the static Main method. Include a switch statement that uses a combination of the HttpMethod and Path from the incoming API event to route to the correct method.

Example of generated code:

public static async Task Main(string[] args)
{
    Func<APIGatewayProxyRequest , Task<APIGatewayProxyResponse>> apiHandler = Handler;
    await Amazon.Lambda.RuntimeSupport.LambdaBootstrapBuilder.Create(apiHandler, new Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer()).Build().RunAsync();
}

public async static Task<APIGatewayProxyResponse> Handler(APIGatewayProxyRequest request)
{
    switch ($"{request.HttpMethod.ToUpper()} {request.Path.ToUpper()}")
    {
        case "GET /products":
            return GetProductsHandler();
        default:
            return new APIGatewayProxyResponse()
            {
                StatusCode = 404
            };
    }
}

Other Information

No response

Acknowledgements

  • [X] I may be able to implement this feature request
  • [ ] This feature might incur a breaking change

AWS .NET SDK and/or Package version used

Amazon.Lambda.Annotations

Targeted .NET Platform

.NET 6, .NET 8

Operating System and version

All

jeastham1993 avatar Nov 16 '23 07:11 jeastham1993

Needs review with the team.

ashishdhingra avatar Nov 16 '23 18:11 ashishdhingra

We have a MACH architecture platform which would really benefit from this feature. We are using .NET8 with AOT and the shape of our APIs and their usage pattern means we don't want to run discreet lambdas for each method. Having the ability to do what is requested here would be very useful to us.

andy-potter-evotix avatar Mar 11 '24 17:03 andy-potter-evotix