How to create a sample API with AWS Lambda and API Gateway using Python
Here's a step-by-step guide on how to create a sample API with AWS Lambda and API Gateway using Python:
Step 1: Create a Lambda Function
- Go to the AWS Lambda console and click on "Create function".
- Choose "Author from scratch" and give your function a name and select "Python 3.8" as the runtime.
- Under "Permissions", choose "Create a new role with basic Lambda permissions".
- Click "Create function".
pythonimport json
def lambda_handler(event, context):
response = {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
return response
Step 2: Test the Lambda Function
- Click on the "Test" button in the top-right corner of the Lambda console.
- Configure a new test event and give it a name.
- Click "Create".
- Click "Test" to run the test event and verify that the function returns the expected output.
Step 3: Create an API Gateway
- Go to the AWS API Gateway console and click "Create API".
- Choose "REST API" and "Build".
- Under "Create a new API", choose "New API" and give your API a name.
- Click "Create API".
Step 4: Create a Resource and Method
- In the left-hand navigation menu of the API Gateway console, click on "Resources".
- Click "Create Resource" and give it a name.
- Click "Create Resource".
- Click "Create Method" and choose "GET" from the dropdown.
- In the "Integration type" dropdown, choose "Lambda Function".
- Choose the region where your Lambda function is located.
- Enter the name of your Lambda function and click "Save".
Step 5: Deploy the API
- In the left-hand navigation menu of the API Gateway console, click on "Actions".
- Choose "Deploy API".
- Choose a deployment stage, such as "Prod" or "Test".
- Click "Deploy".
Step 6: Test the API
- In the left-hand navigation menu of the API Gateway console, click on "Stages".
- Click on the URL for your deployed API.
- Append the resource name to the end of the URL and hit enter.
- Verify that the API returns the expected output.
Congratulations, you have now created a sample API with AWS Lambda and API Gateway using Python! This is just a basic example, but you can use this as a starting point for building more complex APIs that integrate with other AWS services or third-party APIs.
Comments
Post a Comment