We have our CDK project fully set up and deployed to our AWS Account, now is the time to start implementing code on the frontend to call our REST API.
If you used the AWS Command Line Interface (CLI), a configuration file “aws-exports.js” would be put in your source directory automatically. However, since we created everything through the CDK, we will need to do a manual setup to import our existing REST API and Cognito User Pool data.
First, install and add the following import statement to your app’s root entry point. This will be App.js in React.
import Amplify, { Auth } from 'aws-amplify';
Next, we will need to configure authentication for Amplify. We will be using the output saved from our CDK and AWS Account details for the configuration. This part is needed because in our CDK project we made our API require Cognito authentication.
Amplify.configure({
Auth: {
region: 'eu-west' // The region your AWS Account is in
userPoolId: '***' // The User Pool Id printed from CDK
userPoolWebClientId: '***' // Web Client Id printed from CDK
});
Ideally, these configuration details should be Environment Variables so they are not exposed.
We will now configure our API. I’m going to add a custom header so that the JWT Token for authorization is created for every API call. You may not want this for your app and can have it removed. However, when you make a call to an API endpoint that requires authorization, you will need a bearer token in the header otherwise you will receive an “Unauthorized” 401 error response.
Add the following API configuration just below the Auth section.
API: {
endpoints: [
{
name: "ExampleAPIGatewayAPI",
// Endpoint printed in CDK deploy output or found in AWS
// Management Console
endpoint: "https://example.amazonaws.com"
custom_header: async () => {
return {
Authorization:
`Bearer ${(await Auth.currentSession())
.getIdToken()
.getJwtToken()}`,
}
}
}
]
}
You are now ready to call your API! In a new file you can import and install the following:
import { API } from 'aws-amplify';
And then call the endpoint configured in your app’s root with the path name created in the CDK.
API.get("ExampleAPIGatewayAPI", 'example', {})
You can find more examples for using a REST API and Authentication with Amplify in the Amplify Docs. Look under “API (REST)” and “Authentication” for help.
Hope you enjoyed this series, thanks for reading!