Introduction
Today we will discuss on everything you need to know about How to create REST API using API Gateway in simple and easy to follow guide with lots of hands-on examples.
Are you a beginner or want an easy answer to API Gateway related stuff?
You came to the right resource.
More specifically we will discuss:
- Creating methods and resources
- Testing API Gateway endpoints
- Adding Authentication
I have been working in the Software industry for over 23 years now and I have been a software architect, manager, developer and engineer. I am a machine learning and crypto enthusiast with emphasis in security. I have experience in various industries such as entertainment, broadcasting, healthcare, security, education, retail and finance.
How to Setup API Gateway
Before we start writing any code we need to setup our API Gateway end point. API Gateway offers various ways of doing this I list some of them below:
- REST API: This is a standard REST API which we will use below it adds some boilerplate validation for us and some other good features that we will discuss below.
- WebSocket API: If you need to communicate to it via websockets for low latency (this is good for apps) this is a good alternative
- HTTP API: This is a vanilla low latency approach which lacks a lot of abstraction of the options above (we will not be using it)
In order to setup the REST API navigate to the API Gateway section and click on the REST API (for now don’t worry about using the private as it limits requests within the VPC network).
So once you select REST API from the list above go ahead and click build and you will get a screen that looks like the one below.
Fill in the options as seen above and click on Create API. This would give you an empty screen which will basically allow us to start adding endpoints to it along with their validation.
The next step we are going to discuss is focusing on two main things:
- Adding a GET request with model validation
- Adding a POST request with model validation
How to Make an API Gateway POST Resource
First we are going to discuss how to make an API Gateway POST Resource, a resource will encompass three basic things:
- The model for the API request
- The model for the API response
- The parameters and GET request path
So in order to do this we are going to split it up based on what was mentioned earlier. We will be giving emphasis on the format of our model validation and why it’s useful and saves us time from programming things.
In the example below we will create a Person API where we each Person has a first, last and age associated with them. As per REST API standard practices we will be using the GET request to retrieve and the POST to add a new entry. For the sake of simplicity here we will not be modifying the Person but this can also be done as a PUT request. If you want me to extend and add this too drop me a line below and I’ll do that.
How to Make an API Gateway POST Request Model
Creating the POST Request model is what parameters we will be accepting in our API request. This sets the data types along with what to expect. API Gateway abstracts the validation and formatting on what is received at server side along with notifying the client if it’s a Bad Request or not. To do this navigate to the Unbiased Coder API we created and click on models from the side bar.
For the name and type please use the values as shown below and for the schema values you can use the code blob, below the picture.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Person",
"type": "object",
"properties": {
"Name": {
"type": "string"
},
"Surname": {
"type": "string"
},
"Age": {
"description": "Age in years",
"type": "integer",
"minimum": 21
}
},
"required": ["Name", "Surname", "Age"]
}
If this succeeds you should see your model appear on the models side bar of your AWS console view.
How to Make an API Gateway POST Response Model
Now that we have created a Request model we need to do the same thing for the Response we will be sending back to the user. In a similar way this can be seen below.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Result",
"type": "object",
"properties": {
"status": {
"type": "string"
},
"message": {
"type": "string"
},
"code": {
"type": "integer"
}
},
"required": ["status", "message", "code"]
}
The response will contain three items which are good in general to have as part of a REST API:
- status: This can be a simple string with success/failed for quick validation from the app side
- message: This is an information content error for the app/web to pass through to the user
- code: This is an internal more detailed error that can be used for the backend team to debug issues.
I would like to stress out the importance of having such models in place. The reason for validating in both ends front and backend is that there may be various developers and bigger teams and often things may break on either side. So adding a layer of protection here prevents things going out of control and allows an easy error catching in our overall API workflow which we will talk about in a bit.
How to setup an API Gateway POST Resource and Method
We need to take those two models and add start associating them with API methods and resources that we are going to build. The simplest one we will be creating is a person resource that has a POST method.
This can be done easily by first creating a resource and naming it person and then under that resource adding a method in this case we will be adding a POST method. If you did this successfully you should get the screen as shown below which is ready to be filled in to complete our workflow.
The next step is to fill in all the information necessary and to associate our models with what we have here. Under options as seen above click on the Method Request so we can fill in the information necessary. In the screen shown below you can find how we will do the association to the request model we previously created for the Person object.
A few things to note here:
- Request validator for now you can keep it simple just to validate the body content across our model
- Keep Authorization and API empty for now
- Fill in the Request Body with the PersonGetRequest we previously created
Similarly we need to do the same for the response object under the Method Response section but in this case since POST requests.
In order to unlock the response model you may need to expand the Response body for 200.
How to test API Gateway POST Requests
The last thing we need to do to complete this setup is to perform a mock test in our endpoint to ensure everything is working fine. But before we go ahead and perform the test we want to setup a pre-defined response using the mediator Integration response that the API Gateway interface offers to us. This will allow us to just set some values for the response JSON we will be sending back to our test. To do this click on the Integration Response field and under mapping templates define what you want to send back on our test. In our case we will be sending a successful test response message (don’t forget to click save).
In order to do this we simply click on the Test button on our API Gateway workflow and we need to complete the Request Body section as shown below. Since we have validation in place this will return to us the HTTP code with 200 if all tests actually pass. It must be noted for now we do not make any associations with a lambda function to keep it simple. If you would like to see this I would be happy to write about it please drop me a line below.
The important part to notice here is that the API is returning to us Successfully completed execution with status: 200. This is an indication of all the tests passing and things working as expected.
A bonus for our testing is to actually see the response using our own template. This can be done easily if we add integration requests and responses which uses our mapping models. To do this you simply have to go to the integration request and response fields of the workflow and add mappings to some predefined values you would like to test with and what response you want to provide leveraging our template code.
How to Make an API Gateway GET Model
The steps we will be following below follow the same paradigm with the POST model so to avoid repeating the process please check the POST section above for more details.
How to Make an API Gateway GET Request Model
The request model we created for the person object can be leveraged here too since the object type we will be dealing with is the same as above. In the case of a GET request we don’t need to define a request model as GET requests ignore the body and only take parameters.
How to Make an API Gateway GET Response Model
Same as the POST request you can do the same thing for your response model and just call it PersonResponse. The response model we created is generic enough and can be recycled as our standard template for all of the responses we will be using across the API.
How to setup an API Gateway GET Request Resource and Method
The request resource and method can be setup in a similar manner like we did with the POST request earlier.
How to test API Gateway GET Requests
The process for testing this procedure is exactly the same open up the workflow and setup your models for your Request and Response use the updated models. As mock data feel free to specify whatever values you think make sense in this case.
One last thing you may want to do is delete the OPTIONS request if it’s not being used in your REST API. I personally do not have any use for it but some frameworks rely on it to get the available parameters as part of the validation to know what is supported. Finally what you should have ended up with is a view like this (considering you deleted the OPTIONS).
How to add API Gateway Authentication
One thing we will try to cover next is how to add authorization for API Gateway end points. The process for doing this is pretty simple. You have really at a high level two good ways of doing this:
- AWS Cognito: This is a standard user management library that AWS offers and it’s a very good option if you have users that interact with your platform
- API Keys: This is an easier approach if your REST API is just being used programmatically from other clients
In this article to keep things simple we will focus more on using API Keys. An API Key in this case it can be in the form of an HTTP header field that we validate in our requests before allowing them to go through. What this means is that API Gateway will take care of this for us and abstract any boiler plate code we may have to write in our code.
Lets use the GET endpoint in our example so go ahead and open it and click on the Method request option from the interface. This should give you a screen that looks like the one below which is where we need to start adding our authorization. The important part is not to use the Authorization part but make sure the API Key Required is there.
At this point you can go ahead and deploy your API from the menu above. But there’s one last step we need to do here which is creating a new API Key. In order to do this navigate on API Keys from the left side of the panel and click from the drop down create api key as shown below.
Once this is done you should go ahead and save you will see a screen as shown below which is the API Gateway API Key you need to be sending in all of your requests which will be automatically validated. In this case I selected Auto Generate but you can always input your own API Key if you are porting from an existing application that uses a key. Note that this is bad security practice but it may be a temporary work-around until you migrate to a new approach using AWS and key rotations.
Using the string as shown above now you can use it safely in your applications to ensure the requests are validated.
Conclusion
If you found How to create REST API using API Gateway useful and you think it may have helped you please drop me a cheer below I would appreciate it. If you would like to know more about this at a high level Amazon also has a great resource which you can find here. Also their section on explaining API keys is very well documented if you want to drill down into more details on the authentication here.
If you have any questions, comments please post them below I check periodically and try to answer them in the priority they come in. Also if you have any corrections please do let me know and I’ll update the article with new updates or mistakes I did.
What API solution do you use in your projects?
If you would like to learn more about AWS interfaces please take a look at the articles below: