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:

  1. Create  an Amazon DynamoDB table
  2. Create AWS AppSync API
  3. 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

  1. Go to Services > AWS AppSync.
  2. Click Create API.
  3. Select Import DynamoDB table and Start.
  4. Choose the thabolebelo_blog or another table from the dropdown and Import.
  5. 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:

  1. Go to the Settings section of your AppSync API from the left side menu.
  2. Select AWS Lambda as the default authorization mode for your API.
  3. Select the region for your Lambda function.
  4. Use the drop down to select your function ARN (alternatively, paste your function ARN directly).
  5. [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.
  6. [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.