This is a walk through lab based on AWS project. For more details please refer here. This walk through breaks into four parts which are
- Host a static website
- Manage users
- Build serverless backend
- Deploy a RESTful API
Deploy a RESTful API
By far, I think this is the most complicated lab within the 4 parts. In this last lab, we will build an Amazon API Gateway as an entry point for the public to access Lambda function created in Part 3. API Gateway can also integrate with Amazon Cognito, executing Lambda function if user is successfully authenticated by Cognito.
Creating API Gateway:
Navigate to API Gateway service and click “Get Started”.
Choose New API, give your API a name, choose Edge optimized as it is best for pubic services being accessed from internet, then click “Create API”
Next, as mentioned earlier, API Gateway can use Cognito User Pools to authenticate API calls, to be specific, the JWT tokens returned by Cognito. So let’s set API Gateway up.
- Click Authorizers.
- Click Create New Authorizer.
- Give any name you like.
- Click Cognito.
- Click the input field and a list will show up then choose the Cognito User Pool created in Part 2.
- Input “Authorization”
- Hit “Create”.
Finish view.
Next we test if the Authorizer is setup correctly by getting the JWT from frontend first and use the Test function. From browser, append /ride.html to your S3 Static Website endpoint. Refer to Part 1 if you don’t remember. Sign in if you are logged out. Copy the JWT value after signed in.
Back to API Gateway Authorizers page and click “Test” beside “Edit”, input JWT value and click “Test”.
If everything is setup correctly, you will see the response replied by Cognito of the JWT given.
Next we create resource and method. Resource is the sub url the browser will be calling. Method is what the browser uses to call the resource.
Follow the steps below to create a resource. Give it a name, enable CORS and create it.
Click /ride, click “Actions”, Create Method. Choose “POST” in the list and save.
Next, since API Gateway will trigger Lambda to execute action, we configure as below. For Lambda Function, input the name of your Lambda function. Click “OK” if any permission window is shown.
Next we setup the Authorizer authentication with Cognito created a while ago. Click “Method Request”
Click on the “pencil” icon, select the Authorizer just created and save.
Now we need to deploy the API Gateway so it is accessible from internet.
Select “New Stage” and give it a name.
Copy the URL as we will need it in the next step.
Modify the config.js file in S3 as below. Save and replace it on S3.
Finally we can validate our result. Visit your static website url with /ride.html. Click anywhere on the map and click “Request Unicorn”.
You will see an unicorn appear and running to the point you selected. Status messages are also shown on the right side.
And that’s it!
CleanUP
Lastly, refer here to clean up all the resources used in the whole lab!