{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/serverless-rest-api-using-python-and-awslambda/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"0470c4dc-cb45-5794-a6fb-e5d124e324a3","excerpt":"In this article i will explain step by step how you can create REST Api using python and AWS Lambda Step 1: REST API definition Create a .json file to define…","html":"<p>In this article i will explain step by step how you can create REST Api using python and AWS Lambda</p>\n<h4>Step 1: REST API definition</h4>\n<p>Create a <strong><em>.json</em></strong> file to define all the rest api you need to add on your aws api gateway</p>\n<pre><code class=\"language-json\">{\n  \"openapi\": \"3.0.0\",\n  \"info\": {\n    \"title\": \"Notes API\",\n    \"description\": \"This API supports the creation and retrieval of a Notes Object.\",\n    \"contact\": {\n      \"email\": \"singhanku658@gmail.com\"\n    },\n    \"license\": {\n      \"name\": \"Apache 2.0\",\n      \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n    },\n    \"version\": \"1.0.0\"\n  },\n  \"servers\": [\n    {\n      \"url\": \"\",\n      \"description\": \"SwaggerHub API Auto Mocking\"\n    }\n  ],\n  \"tags\": [\n    {\n      \"name\": \"admins\",\n      \"description\": \"Secured Admin-only calls\"\n    },\n    {\n      \"name\": \"developers\",\n      \"description\": \"Operations available to regular developers\"\n    }\n  ],\n  \"paths\": {\n    \"/pet\": {\n      \"get\": {\n        \"tags\": [\"developers\"],\n        \"summary\": \"Find note by ID\",\n        \"description\": \"Returns the matching note object\",\n        \"operationId\": \"findNote\",\n        \"parameters\": [\n          {\n            \"name\": \"id\",\n            \"in\": \"query\",\n            \"description\": \"ID of the note to return\",\n            \"required\": true,\n            \"style\": \"form\",\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Note object matching criteria\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Note\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Note not found\"\n          }\n        }\n      },\n      \"post\": {\n        \"tags\": [\"developers\"],\n        \"summary\": \"Adds a note with form data\",\n        \"description\": \"Adds a note object to the system\",\n        \"operationId\": \"addNote\",\n        \"requestBody\": {\n          \"description\": \"Note to add\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Note\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Note object created\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Note\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"invalid input, object invalid\"\n          },\n          \"409\": {\n            \"description\": \"an existing note already exists\"\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"Note\": {\n        \"required\": [\"name\", \"description\", \"createdOn\"],\n        \"type\": \"object\",\n        \"properties\": {\n          \"name\": {\n            \"type\": \"string\",\n            \"example\": \"My Note\"\n          },\n          \"description\": {\n            \"type\": \"string\",\n            \"example\": \"My Description\"\n          },\n          \"createdOn\": {\n            \"type\": \"string\",\n            \"format\": \"date\",\n            \"example\": \"2012-05-15\"\n          }\n        }\n      }\n    }\n  }\n}\n</code></pre>\n<h4>Step 2: Create Cloudformation template for setting up our serverless infrastructure</h4>\n<ul>\n<li>Login to your aws account and got to cloud formation and click on create stack-> With existing resources(imported resources)</li>\n</ul>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/Serverless-Rest-API-using-python-AWS-Lambda-1.png\" alt=\"create-stack\"></p>\n<ul>\n<li>\n<p>Selecting the template file and click Next</p>\n</li>\n<li>\n<p>Name the new stack NoteAPI or something similar and then click Next</p>\n</li>\n<li>\n<p>Keep all the default options on the Configure stack options page and click Next</p>\n</li>\n<li>\n<p>At the bottom of the Review page, check the option to allow CloudFormation to create an IAM role.</p>\n</li>\n<li>\n<p>Copy paste below snippet to and save it in a <strong><em><em>.json</em></em></strong> file and use it to create lambda function and dynamodb</p>\n</li>\n</ul>\n<pre><code class=\"language-json\">{\n  \"AWSTemplateFormatVersion\": \"2010-09-09\",\n  \"Description\": \"AWS CloudFormation Template To Create a DynamoDB with Lambda Role\",\n  \"Parameters\": {\n    \"HashKeyElementName\": {\n      \"Type\": \"String\",\n      \"Default\": \"id\",\n      \"Description\": \"Hash Key Name\"\n    },\n    \"HashKeyElementType\": {\n      \"Type\": \"String\",\n      \"Default\": \"S\",\n      \"Description\": \"Hash Key Type\"\n    }\n  },\n  \"Resources\": {\n    \"DynamoDBTable\": {\n      \"Type\": \"AWS::DynamoDB::Table\",\n      \"Properties\": {\n        \"TableName\": \"Notes\",\n        \"AttributeDefinitions\": [\n          {\n            \"AttributeName\": {\n              \"Ref\": \"HashKeyElementName\"\n            },\n            \"AttributeType\": {\n              \"Ref\": \"HashKeyElementType\"\n            }\n          }\n        ],\n        \"KeySchema\": [\n          {\n            \"AttributeName\": {\n              \"Ref\": \"HashKeyElementName\"\n            },\n            \"KeyType\": \"HASH\"\n          }\n        ],\n        \"ProvisionedThroughput\": {\n          \"ReadCapacityUnits\": 1,\n          \"WriteCapacityUnits\": 1\n        }\n      }\n    },\n    \"FunctionSet\": {\n      \"Type\": \"AWS::Lambda::Function\",\n      \"Properties\": {\n        \"FunctionName\": \"NoteLambda-Set\",\n        \"Handler\": \"index.lambda_handler\",\n        \"Runtime\": \"python3.7\",\n        \"Code\": {\n          \"ZipFile\": \"import json\\ndef handler(event, context) :\\n  print(\\\"Event: %s\\\" % json.dumps(event))\\n\"\n        },\n        \"Role\": {\n          \"Fn::GetAtt\": [\"LambdaExecutionRole\", \"Arn\"]\n        },\n        \"Timeout\": \"2\"\n      },\n      \"DependsOn\": [\"LambdaExecutionRole\"]\n    },\n    \"FunctionGet\": {\n      \"Type\": \"AWS::Lambda::Function\",\n      \"Properties\": {\n        \"FunctionName\": \"NoteLambda-Get\",\n        \"Handler\": \"index.lambda_handler\",\n        \"Runtime\": \"python3.7\",\n        \"Code\": {\n          \"ZipFile\": \"import json\\ndef handler(event, context) :\\n  print(\\\"Event: %s\\\" % json.dumps(event))\\n\"\n        },\n        \"Role\": {\n          \"Fn::GetAtt\": [\"LambdaExecutionRole\", \"Arn\"]\n        },\n        \"Timeout\": \"2\"\n      },\n      \"DependsOn\": [\"LambdaExecutionRole\"]\n    },\n    \"LambdaExecutionRole\": {\n      \"Type\": \"AWS::IAM::Role\",\n      \"Properties\": {\n        \"Policies\": [\n          {\n            \"PolicyName\": \"LambdaPolicy\",\n            \"PolicyDocument\": {\n              \"Version\": \"2012-10-17\",\n              \"Statement\": [\n                {\n                  \"Action\": [\n                    \"logs:CreateLogGroup\",\n                    \"logs:CreateLogStream\",\n                    \"logs:PutLogEvents\"\n                  ],\n                  \"Resource\": [\"arn:aws:logs:*:*:*\"],\n                  \"Effect\": \"Allow\"\n                },\n                {\n                  \"Action\": [\"dynamodb:PutItem\", \"dynamodb:GetItem\"],\n                  \"Resource\": {\n                    \"Fn::GetAtt\": [\"DynamoDBTable\", \"Arn\"]\n                  },\n                  \"Effect\": \"Allow\"\n                }\n              ]\n            }\n          }\n        ],\n        \"AssumeRolePolicyDocument\": {\n          \"Version\": \"2012-10-17\",\n          \"Statement\": [\n            {\n              \"Action\": [\"sts:AssumeRole\"],\n              \"Effect\": \"Allow\",\n              \"Principal\": {\n                \"Service\": [\"lambda.amazonaws.com\"]\n              }\n            }\n          ]\n        }\n      }\n    }\n  }\n}\n</code></pre>\n<ul>\n<li>\n<p>Once you complete the above step it will create a dynamoDB table named Notes with primary key named id</p>\n</li>\n<li>\n<p>Create An IAM Role that grants a Lambda function with permission to write and read to dynamodb table</p>\n</li>\n<li>\n<p>Create two lambda function one for get and one for post</p>\n</li>\n</ul>\n<h4>Step 3: Writing code to lambda function</h4>\n<ul>\n<li>\n<p>On the AWS Console navigate to lambda home page and there would be two function created using our cloudformation template above</p>\n</li>\n<li>\n<p>We will select NoteLambda-Set function and write code to insert data to dynamodb, open index.py file and copy paste below code snippet</p>\n</li>\n</ul>\n<pre><code class=\"language-py\">import boto3\ndef lambda_handler(event, context):\n   client = boto3.resource('dynamodb')\n   table = client.Table('Notes')\n   response = table.put_item(\n       Item={\n           'id': event['id'],\n           'name': event['name'],\n           'description': event['description'],\n           'createdOn': event['createdOn']\n       }\n   )\n   return {\n       'statusCode': response['ResponseMetadata']['HTTPStatusCode'],\n       'body': 'Record ' + event['id'] + ' added'\n   }\n</code></pre>\n<ul>\n<li>Now update the NoteLambda-Set function open index.py file and copy paste the following code snippet</li>\n</ul>\n<pre><code class=\"language-py\">import boto3\ndef lambda_handler(event, context):\n   client = boto3.resource('dynamodb')\n   table = client.Table('Notes')\n   response = table.get_item(\n       Key={\n           'id': event['id']\n       }\n   )\n   if 'Item' in response:\n       return response['Item']\n   else:\n       return {\n           'statusCode': '404',\n           'body': 'Not found'\n       }\n</code></pre>\n<h4>Step 4: Create API Gateway</h4>\n<p>Navigate to API Gateway in your aws console and do the following steps</p>\n<ul>\n<li>Click the Import button and select the Import from Swagger or Open API 3 option and then select the .json file created\nin Step 1 above</li>\n<li>Once done importing you will see Get and Post API and now we will setup Get and POST, Click on setup post endpoint</li>\n<li>Set the integration type to Lambda function region will be same as lambda function</li>\n<li>Type the name of the lambda function in the lambda function field and click save</li>\n</ul>\n<p>Configuring the GET endpoint</p>\n<ul>\n<li>Click Set up now for the GET endpoint.</li>\n<li>Set the Integration type to Lambda Function. The region is the same one where you defined your functions.</li>\n<li>Type NoteLambda-Get into the Lambda Function field and select Save.</li>\n<li>AWS will prompt you again to add permissions for the API Gateway to call your function, so click OK.</li>\n<li>Select the Method Request box</li>\n<li>Under URL Query String Parameters add a query string named id, and mark it as required.</li>\n<li>Click the checkmark to save it.</li>\n<li>Select Method Execution to return to the main configuration page for the GET endpoint.</li>\n<li>Select the Integration Request box.</li>\n<li>Under Mapping Templates, select When there are no templates defined (recommended).</li>\n<li>Select the option to Add mapping template.</li>\n<li>Set the Content-Type to application/json and select the checkmark to save the value.</li>\n<li>In the Generate Template box, paste the following:</li>\n</ul>\n<pre><code class=\"language-json\">{\n  \"id\": \"$input.params('id')\"\n}\n</code></pre>\n<ul>\n<li>This configuration will map the query string parameter to an input parameter for the Lambda. Click Save when you’re done.</li>\n</ul>\n<h4>Step 5: Deploy and test API gateway</h4>\n<ul>\n<li>From the main screen for your API, click on Actions, and choose Deploy API.</li>\n<li>Choose [New Stage] from the Deployment stage dropdown, and then enter a name and click deploy</li>\n<li>Once deployed you will find custom URL at the top of the page copy the url and paste in the browser and just add\n/note?id=d290f1ee-6c54-4b01-90e6-d701748f0851</li>\n</ul>","fields":{"slug":"/serverless-rest-api-using-python-and-awslambda/"},"frontmatter":{"title":"Serverless Rest API using python and AWS Lambda","date":"May 30, 2023","description":"In this article i will explain you step by step how you can create serverless rest api using python and AWS Lambda","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/serverless.jpeg"}},"previous":{"fields":{"slug":"/serverless-api-using-nodejs-lambda/"},"frontmatter":{"title":"Serverless Rest API using nodejs and AWS Lambda","date":"May 15, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/serverless-node.jpeg"}},"next":{"fields":{"slug":"/testing-using-jest-and-puppeteer-javascript/"},"frontmatter":{"title":"Testing using jest and puppeteer in nodejs","date":"June 01, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/puppetter.jpeg"}}},"pageContext":{"id":"0470c4dc-cb45-5794-a6fb-e5d124e324a3","previousPostId":"58348641-da6b-517b-8c01-a88b84257a9e","nextPostId":"e0ea46b7-1202-5ffc-88c2-6e2236f40254"}},
    "staticQueryHashes": ["3860684146"]}