How to Intermediate · 3 min read

How to use Bedrock with API Gateway

Quick answer
Use boto3 to call the bedrock-runtime client within an AWS Lambda function triggered by API Gateway. Configure API Gateway to proxy requests to Lambda, which invokes client.converse() or client.invoke_model() to interact with Bedrock models securely.

PREREQUISITES

  • Python 3.8+
  • AWS CLI configured with appropriate IAM permissions
  • boto3 installed (pip install boto3)
  • An AWS Bedrock-enabled account
  • API Gateway and Lambda setup permissions

Setup

Install boto3 and configure AWS CLI with credentials that have permissions for Bedrock, Lambda, and API Gateway. Create an AWS Lambda function with a Python runtime and attach an execution role allowing Bedrock invocation. Set up an API Gateway REST API to trigger the Lambda function.

bash
pip install boto3

Step by step

This example shows a Python AWS Lambda handler that receives a JSON payload from API Gateway, calls AWS Bedrock's converse method to invoke a model, and returns the AI response.

python
import json
import boto3

client = boto3.client('bedrock-runtime')

def lambda_handler(event, context):
    # Extract user input from API Gateway event
    body = json.loads(event.get('body', '{}'))
    user_input = body.get('input', 'Hello Bedrock')

    # Call Bedrock converse API
    response = client.converse(
        modelId='anthropic.claude-3-5-sonnet-20241022-v2:0',
        messages=[{'role': 'user', 'content': [{'type': 'text', 'text': user_input}]}]
    )

    # Extract text from response
    output_text = response['output']['message']['content'][0]['text']

    # Return response to API Gateway
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps({'response': output_text})
    }
output
{
  "response": "Hello Bedrock"
}

Common variations

  • Use invoke_model for raw JSON payloads if you need more control over the request.
  • Switch models by changing the modelId parameter.
  • Implement async Lambda handlers with asyncio if your environment supports it.
  • Use API Gateway HTTP APIs for simpler setup and lower latency.

Troubleshooting

  • If you get AccessDeniedException, verify your Lambda execution role has bedrock:InvokeModel permission.
  • For InvalidParameterException, check your modelId and message format.
  • Enable detailed CloudWatch logs for Lambda to debug request/response payloads.
  • Ensure API Gateway integration request and response mappings are correctly configured to pass JSON.

Key Takeaways

  • Use AWS Lambda as a secure backend to invoke Bedrock models via API Gateway.
  • The bedrock-runtime boto3 client supports converse and invoke_model methods for AI inference.
  • Proper IAM permissions and API Gateway integration setup are critical for successful Bedrock API calls.
Verified 2026-04 · anthropic.claude-3-5-sonnet-20241022-v2:0
Verify ↗