Generate a GraphQL API from a DynamoDB Table
AWS AppSync can automatically create a GraphQL schema from existing Amazon DynamoDB tables. This can be useful if you have DynamoDB tables that you want to expose data through a GraphQL endpoint, or if you’re more comfortable starting first with your database design instead of a GraphQL schema.
Below is a few steps we will go through to create a GraphQL API using DynamoDB table:
- Create an Amazon DynamoDB table
- Create AWS AppSync API
- Set up AWS Lambda as an authorization mode
Step 1: Create a DynamoDB Table
If you already have a DynamoDB table you want to use, feel free to use it. If not, then visit Import JSON Data into DynamoDB to create a table of posts.
Step 2: Create AWS AppSync API
- Go to Services > AWS AppSync.
- Click Create API.
- Select Import DynamoDB table and Start.
- Choose the thabolebelo_blog or another table from the dropdown and Import.
- Keep all the defaults and Create
Step 3: Set up AWS Lambda as an authorization mode
With Lambda authorization you specify a Lambda function with custom business logic that determines if requests should be authorized and resolved by AppSync.
Note that you can only have a single AWS Lambda function configured to authorize your API.
You can follow AWS AppSync Authorization using Lambda to configure AWS Lambda as an additional authorization mode. Next follow the steps:
- Go to the Settings section of your AppSync API from the left side menu.
- Select AWS Lambda as the default authorization mode for your API.
- Select the region for your Lambda function.
- Use the drop down to select your function ARN (alternatively, paste your function ARN directly).
- [Optional] Enter a TTL that specifies how long to cache the response from Lambda. The cache key is
<api-id, authorization-token>
. Using a TTL and caching your Lambda function’s response avoids repeated function invocations, and optimizes for cost. - [Optional] Enter a regular expression to allow or block requests based on the
Authorization
header value. Setting up a regular expression filters out unexpected requests, avoid unnecessary function invocations, and optimizes for cost.
The lambda function checks the authorization token and if the value is thabolebelo
, the request is allowed. You can mix and match Lambda with all the other AppSync authorization modes in a single API to enhance security and protect your GraphQL data backends and clients.
Note: You need to provide a valid Authorization Token to get the API data.
Summary
This was just scratching the surface on how to fast-track GraphQL API creation using AWS AppSync. We can automatically create a GraphQL schema and connect resolvers to existing Amazon DynamoDB tables.