Automating AWS API Gateway and Lambda Integration with Boto3 in Python

 Setting up AWS API Gateway endpoints and integrating them with Lambda functions can be a repetitive and error-prone task when done manually through the AWS Management Console. Automating this process using Python's Boto3 library not only saves time but also ensures consistency across deployments.

Prerequisites

Before diving into the automation script, ensure you have the following:

  • AWS CLI Configured: Set up with the necessary credentials and default region.

  • Python 3.x Installed: Along with the Boto3 library. If not installed, you can do so using:

    pip install boto3
  • Existing Lambda Function: Ensure you have a Lambda function created. For this example, we'll refer to it as xxxx.

The Automation Script

The following Python script performs the following actions:

  1. Creates a REST API named SDKStatsAPI.

  2. Adds a /stats resource to the API.

  3. Configures a GET method on the /stats resource, integrating it with the specified Lambda function.

  4. Enables CORS by setting up an OPTIONS method with the appropriate headers.

  5. Deploys the API to a stage named prod.

  6. Grants API Gateway permission to invoke the Lambda function.

Here's the script:


import boto3 import json # Initialize clients apigateway = boto3.client('apigateway', region_name='us-east-1') lambda_client = boto3.client('lambda', region_name='us-east-1') # Define variables api_name = 'SDKStatsAPI' resource_path = 'stats' lambda_function_name = 'xxxx' # Replace with your actual Lambda function name account_id = boto3.client('sts').get_caller_identity().get('Account') lambda_arn = f'arn:aws:lambda:us-east-1:{account_id}:function:{lambda_function_name}' stage_name = 'prod' # 1. Create REST API api_response = apigateway.create_rest_api( name=api_name, description='API for SDKStats Lambda function' ) api_id = api_response['id'] print(f"Created REST API with ID: {api_id}") # 2. Get Root Resource ID resources = apigateway.get_resources(restApiId=api_id) root_id = next(item['id'] for item in resources['items'] if item['path'] == '/') # 3. Create /stats Resource resource_response = apigateway.create_resource( restApiId=api_id, parentId=root_id, pathPart=resource_path ) resource_id = resource_response['id'] print(f"Created resource '/{resource_path}' with ID: {resource_id}") # 4. Create GET Method apigateway.put_method( restApiId=api_id, resourceId=resource_id, httpMethod='GET', authorizationType='NONE' ) # 5. Integrate GET Method with Lambda apigateway.put_integration( restApiId=api_id, resourceId=resource_id, httpMethod='GET', type='AWS_PROXY', integrationHttpMethod='POST', uri=f'arn:aws:apigateway:us-east-1:lambda:path/2015-03-31/functions/{lambda_arn}/invocations' ) # 6. Enable CORS by Adding OPTIONS Method # a. Create OPTIONS Method apigateway.put_method( restApiId=api_id, resourceId=resource_id, httpMethod='OPTIONS', authorizationType='NONE' ) # b. Set up Mock Integration for OPTIONS apigateway.put_integration( restApiId=api_id, resourceId=resource_id, httpMethod='OPTIONS', type='MOCK', requestTemplates={ 'application/json': '{"statusCode": 200}' } ) # c. Add Method Response for OPTIONS apigateway.put_method_response( restApiId=api_id, resourceId=resource_id, httpMethod='OPTIONS', statusCode='200', responseParameters={ 'method.response.header.Access-Control-Allow-Headers': False, 'method.response.header.Access-Control-Allow-Methods': False, 'method.response.header.Access-Control-Allow-Origin': False }, responseModels={ 'application/json': 'Empty' } ) # d. Add Integration Response for OPTIONS apigateway.put_integration_response( restApiId=api_id, resourceId=resource_id, httpMethod='OPTIONS', statusCode='200', responseParameters={ 'method.response.header.Access-Control-Allow-Headers': "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'", 'method.response.header.Access-Control-Allow-Methods': "'GET,OPTIONS'", 'method.response.header.Access-Control-Allow-Origin': "'*'" }, responseTemplates={ 'application/json': '' } ) # 7. Deploy the API deployment = apigateway.create_deployment( restApiId=api_id, stageName=stage_name ) print(f"Deployed API to stage: {stage_name}") # 8. Grant API Gateway Permission to Invoke Lambda lambda_client.add_permission( FunctionName=lambda_function_name, StatementId='APIGatewayInvokePermission', Action='lambda:InvokeFunction', Principal='apigateway.amazonaws.com', SourceArn=f'arn:aws:execute-api:us-east-1:{account_id}:{api_id}/*/GET/{resource_path}' ) # 9. Output the Invoke URL invoke_url = f'https://{api_id}.execute-api.us-east-1.amazonaws.com/{stage_name}/{resource_path}' print(f"API Endpoint: {invoke_url}")

Execution Steps

  1. Save the Script: Save the above script to a file, e.g., setup_api_gateway.py.

  2. Run the Script: Execute the script using Python:

    python setup_api_gateway.py
  3. Access the API Endpoint: Upon successful execution, the script will output the API endpoint URL. You can use this URL to invoke your Lambda function via HTTP GET requests.

Conclusion

By automating the integration of AWS API Gateway with Lambda functions using Python's Boto3 library, you can significantly streamline your deployment processes, reduce the potential for human error, and ensure consistency across different environments.

This approach is especially beneficial for teams adopting Infrastructure as Code (IaC) practices, enabling version control and repeatable deployments.

Comments

Popular posts from this blog

Building and Deploying a Fargate Container that runs Python and performs CloudWatch Logging

Setting up an AWS Cognito User Pool and building a React login component

Deploying a Java web application to Amazon ECS