Right when we first started to use the AWS API Gateway, one of the things that did bother us was the fact that we had to manage lot of resources spread into 1,000s of lines of a couple of Terraform files, and it was a lot of work that required attention and time, things that are critical in software development as we all know.
Basically, when we are developing a new API, we need to create a 3 resources in the API Gateway. We need to create a new gateway_resource, a new gateway_method and a new gateway_integration, and therefore connecting all of them using their respectives IDs.
Now we can create a module to help us. We can start by creating a separate folder which will be our module, let's call it `terraform/modules/api`, inside of it there will be a couple of files:
Here we will define the variables that we will use in the module, what will come from the outside. Note that here it's just the essencial, you will add more things as you need.
This file is needed for at least one important variable, which is the `resource_id`. That's needed if we have some endpoint like `/users/all/prune` which needs a `parent_id`.
Since we need one `aws_api_gateway_method` for each HTTP Method, we use the `count` to iterate over the list of HTTP Methods and create one api_gateway_method for each http method we defined in the `var.http_methods` list.
Now that we have the module, we can use it in our `main.tf` file. We will use the same example as before, but now we will use the module and we will create some other endpoints as example as well.
```terraform
# this is our main API endpoint, we don't want to receive any request here, so we will only create the resource
For one endpoint, we went from having to manage 15 lines splitted in 3 files to just 5 lines inside of one file. If you have to manage hundreds of endpoints, that will be a great help.
We can also add the `WWW-Authenticate` header to the request for example. We tried to do that by adding it to the files properly, but it didn't work. The reason was that the API Gateway was not passing the `WWW-Authenticate` to our API, and that's because of the name of the header. You can call it `WWW-Authenticate-Header` for example and it will work.
This code has not been tested "as is", but it has been tested as part of a bigger project. There is always room for improvements and more possibilities depending on the context, but it's a good start.
There has been a lot of pieces of Terraform code that was omitted, like when we use the declare the `terraform_remote_state` or the `authorizer_id` which you will need if using authorization "CUSTOM".