Search code examples
aws-lambdaterraformaws-api-gateway

Mapping routes with Terraform and API Gateway


I am building an API with AWS Lambda and API Gateway, keeping infrastructure in terraform. I have been mapping each route in my API to API Gateway using the terraform resource aws_apigatewayv2_route; if I do not, I get a 404 error. Rather than having to map each route to terraform is there a way to map all routes by default and then let the actual API code handle 404 errors? This is primarily to not have to change terraform every time I add a new endpoint to my API.

This is one route example:

resource "aws_apigatewayv2_route" "one_single_route" {
  api_id    = aws_apigatewayv2_api.my_api.id
  route_key = "POST /one-single-route"
  target    = "integrations/${aws_apigatewayv2_integration.my_integration.id}"
}

can I do something like this instead:

resource "aws_apigatewayv2_route" "all_routes" {
  api_id    = aws_apigatewayv2_api.my_api.id
  route_key = "ALL /*"
  target    = "integrations/${aws_apigatewayv2_integration.my_integration.id}"
}

Solution

  • In API Gateway you can define a greedy path with ANY method to forward all requests to your integration lambda.

    Update your:

    route_key = "ALL /*"
    

    To:

    route_key = "ANY /{proxy+}"
    

    https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-routes.html