├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── graphql-lambda ├── __init__.py ├── lambda_function.py ├── requirements.txt └── schema.py ├── images └── graphql.png └── template.yaml /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *main* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software is furnished to do so. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 10 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 11 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 12 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 13 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 14 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-serverless-graphql-dynamodb 2 | 3 | This project provides a sample code to implement API GW GraphQL API's (sample code uses python grpahql library Graphene) in Lambda function to create and read the record from DynamoDB Table. The sample code also do have a SAM template for easy deployment. 4 | 5 | This sample can be used as reference to implement GraphQL API using API GW/Lambda which needs data to be written to and read from DynamoDB. 6 | 7 | ## Pre-requisites: 8 | 9 | 1. You need to have AWS Account and setup Access keys 10 | 2. You need to have SAM CLI Installed already. Follow the link for details and installation of SAM CLI: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html 11 | 3. Docker (To do build) 12 | 13 | ## Architecture 14 | 15 | ![Architecture](images/graphql.png) 16 | 17 | ## Steps to setup 18 | 19 | 1. Clone the repo 20 | 2. Build using the command sam build --template template.yaml --use-container 21 | 3. Deploy using the command sam deploy --guided 22 | 23 | ## Example Queries 24 | ### Add a new entry 25 | /graphql?query="mutation addnewentry{empData(empEntry: {empId: 1, empName: "abc", empTitle: "architect", empStartDate: "14-Jan-2021" }) {empId empName empTitle empStartDate}}" 26 | 27 | ### Get all the records of employees 28 | /graphql?query="{allEmpData{empInfo}}" 29 | 30 | ### Get the record of specific employee using employee id 31 | #### To receive only employee name who belong to provided employee id 32 | /graphql?query="{empDetails(empId: 1) { empName }}" 33 | #### To receive only employee start data who belong to provided employee id 34 | /graphql?query="{empDetails(empId: 1) { empStartDate }}" 35 | #### To receive only employee title who belong to provided employee id 36 | /graphql?query="{empDetails(empId: 1) { empTitle }}" 37 | #### To receive only employee name, title and start date who belong to provided employee id 38 | /graphql?query="{empDetails(empId: 1) { empName empTitle empStartDate }}" 39 | 40 | ## Cleanup 41 | 42 | To delete the deployment created using sam deploy, use the AWS CLI command. Assuming you used the project name for the stack name, you can execute the following command: 43 | 44 | ```bash 45 | aws cloudformation delete-stack --stack-name aws-serverless-graphql-dynamodb 46 | ``` 47 | ## Security 48 | 49 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 50 | 51 | ## License 52 | 53 | This library is licensed under the MIT-0 License. See the LICENSE file. 54 | -------------------------------------------------------------------------------- /graphql-lambda/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-graphql-dynamodb/25a5b3daed07287952ce4b8a89eca64ff4008b66/graphql-lambda/__init__.py -------------------------------------------------------------------------------- /graphql-lambda/lambda_function.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this 5 | # software and associated documentation files (the "Software"), to deal in the Software 6 | # without restriction, including without limitation the rights to use, copy, modify, 7 | # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | # permit persons to whom the Software is furnished to do so. 9 | # 10 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 11 | # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 12 | # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 13 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 14 | # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 15 | # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 16 | # 17 | 18 | import json 19 | from schema import empSchema 20 | 21 | def lambda_handler(event, context): 22 | print("Event Parameters:%s" %event) 23 | result = {} 24 | try: 25 | response = empSchema.execute(event['queryStringParameters']['query']) 26 | print("Response from Graphene:%s" %response) 27 | if response.data: 28 | result = {'statusCode': 200, 'body': json.dumps(response.data)} 29 | else: 30 | result = {'statusCode': 500, 'body': json.dumps(response.errors[0].message)} 31 | except Exception as e: 32 | result = {'statusCode': 500, 'body': "An error occurred:%s" %e} 33 | return result 34 | -------------------------------------------------------------------------------- /graphql-lambda/requirements.txt: -------------------------------------------------------------------------------- 1 | boto3 2 | graphene -------------------------------------------------------------------------------- /graphql-lambda/schema.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: MIT-0 3 | # 4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this 5 | # software and associated documentation files (the "Software"), to deal in the Software 6 | # without restriction, including without limitation the rights to use, copy, modify, 7 | # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to 8 | # permit persons to whom the Software is furnished to do so. 9 | # 10 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 11 | # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 12 | # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 13 | # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 14 | # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 15 | # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 16 | # 17 | 18 | from graphene import ObjectType, InputObjectType, String, Int, Schema, Field, DateTime, Mutation, JSONString 19 | import boto3 20 | 21 | DYNAMO_DB_TABLE_NAME = 'demoempdb' 22 | 23 | def getItemFromDynamoDb(tableName, empId, param=None): 24 | #Code to get the item into dynamo db 25 | dynamodb = boto3.resource('dynamodb') 26 | table = dynamodb.Table(tableName) 27 | response = table.get_item(Key={'empId': empId}) 28 | print(response['Item']) 29 | result = response['Item'] 30 | if param: 31 | result = response['Item'][param] 32 | print(result) 33 | return result 34 | 35 | def getAllItemsFromDynamoDbTable(tableName): 36 | results = [] 37 | lastEvaluatedKey = None 38 | client = boto3.client('dynamodb') 39 | while True: 40 | if lastEvaluatedKey: 41 | response = client.scan( 42 | TableName=tableName, 43 | ExclusiveStartKey=last_evaluated_key 44 | ) 45 | else: 46 | response = client.scan(TableName=tableName) 47 | lastEvaluatedKey = response.get('LastEvaluatedKey') 48 | results.extend(response['Items']) 49 | if not lastEvaluatedKey: 50 | break 51 | return results 52 | 53 | class DemoEmployeeParamsInput(InputObjectType): 54 | empId = Int(required=True) 55 | empName = String(required=True) 56 | empTitle = String(required=True) 57 | empStartDate = String(required=True) 58 | 59 | class DemoEmployeeParams(ObjectType): 60 | class Meta: 61 | description = 'Employee Parameters' 62 | empId = Int() 63 | empName = String() 64 | empTitle = String() 65 | empStartDate = String() 66 | empInfo = JSONString() 67 | 68 | class CreateEntry(Mutation): 69 | class Arguments: 70 | empEntry = DemoEmployeeParamsInput(required=True) 71 | 72 | Output = DemoEmployeeParams 73 | def mutate(self, info, empEntry): 74 | #Code to add the item into dynamo db 75 | dynamodb = boto3.resource('dynamodb') 76 | table = dynamodb.Table(DYNAMO_DB_TABLE_NAME) 77 | table.put_item(Item=empEntry) 78 | return DemoEmployeeParams( 79 | empId = empEntry.empId, 80 | empName = empEntry.empName, 81 | empTitle = empEntry.empTitle, 82 | empStartDate = empEntry.empStartDate 83 | ) 84 | 85 | class Mutation(ObjectType): 86 | empData = CreateEntry.Field() 87 | 88 | class Query(ObjectType): 89 | empDetails = Field(DemoEmployeeParams, empId=Int(required=True)) 90 | allEmpData = Field(DemoEmployeeParams) 91 | 92 | def resolve_allEmpData(root, info): 93 | #Query the dynamodb here and get all the records for display 94 | data = {} 95 | data['empInfo'] = getAllItemsFromDynamoDbTable(DYNAMO_DB_TABLE_NAME) 96 | return data 97 | 98 | def resolve_empDetails(root, info, empId): 99 | data = {} 100 | data = getItemFromDynamoDb(DYNAMO_DB_TABLE_NAME, empId) 101 | return data 102 | 103 | empSchema = Schema(query=Query, mutation=Mutation) -------------------------------------------------------------------------------- /images/graphql.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/aws-serverless-graphql-dynamodb/25a5b3daed07287952ce4b8a89eca64ff4008b66/images/graphql.png -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: '2010-09-09' 2 | Transform: AWS::Serverless-2016-10-31 3 | Description: > 4 | Sample SAM Template for aws-serverless-graphql-dynamodb 5 | 6 | # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst 7 | Globals: 8 | Function: 9 | Timeout: 3 10 | 11 | Resources: 12 | DemoGraphQLApi: 13 | Type: AWS::Serverless::Api 14 | Properties: 15 | StageName: Prod 16 | DemoGraphQLFunction: 17 | Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction 18 | Properties: 19 | CodeUri: graphql-lambda/ 20 | Handler: lambda_function.lambda_handler 21 | Runtime: python3.8 22 | Policies: 23 | # Give DynamoDB Full Access to your Lambda Function 24 | - AmazonDynamoDBFullAccess 25 | Events: 26 | GraphQLQuery: 27 | Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api 28 | Properties: 29 | RestApiId: !Ref DemoGraphQLApi 30 | Path: /graphql 31 | Method: post 32 | DemoDB: 33 | Type: AWS::Serverless::SimpleTable 34 | Properties: 35 | TableName: demoempdb 36 | PrimaryKey: 37 | Name: empId 38 | Type: Number 39 | ProvisionedThroughput: 40 | ReadCapacityUnits: 5 41 | WriteCapacityUnits: 5 42 | Outputs: 43 | # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function 44 | # Find out more about other implicit resources you can reference within SAM 45 | # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api 46 | DemoGraphQLApi: 47 | Description: "API Gateway endpoint URL for Prod stage for Demo Backend function" 48 | Value: !Sub "https://${DemoGraphQLApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/graphql/" 49 | DemoGraphQLFunction: 50 | Description: "GraphQL Lambda Function ARN" 51 | Value: !GetAtt DemoGraphQLFunction.Arn 52 | 53 | --------------------------------------------------------------------------------