> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Exposing Your Bedrock App Using API Gateway Part 1

> Shows how to build a serverless event driven pipeline using S3, Lambda, and Amazon Bedrock to automatically process incoming data with generative AI and store results

In this lesson you’ll learn how to integrate Amazon Bedrock with AWS Lambda so generative AI tasks run automatically whenever new data arrives. This serverless, event-driven approach makes real-time processing scalable, resilient, and cost-effective.

Lesson outline:

* Define the real-world problem: inefficient handling of real-time data.
* Present a serverless, event-driven solution using Lambda and Bedrock.
* Walk through the implementation workflow and sample code.
* Explain expected results, benefits, and operational considerations.
* Provide next steps for a hands-on implementation.

Let’s start with the real-world problem.

When new data assets arrive in a storage service, you often want to react automatically. New data can come from IoT devices, batch processes, customer uploads, reviews, or surveys, and it frequently arrives in unpredictable bursts. A manual flow—notify a person (email), have them trigger an AI workflow, then wait for results—is slow, inconsistent, and hard to scale because it depends on human intervention.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/tJmUiudNjsCWp_bm/images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/manual-ai-realtime-data-workflow-inefficient.jpg?fit=max&auto=format&n=tJmUiudNjsCWp_bm&q=85&s=ea8cfe501f6abddded76fcfaf2f7edeb" alt="A slide showing an inefficient real-time data workflow: new data triggers a manual AI workflow start which then begins processing, with the issues labeled as &#x22;Slow,&#x22; &#x22;Inconsistent,&#x22; and &#x22;Difficult to scale.&#x22;" width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/manual-ai-realtime-data-workflow-inefficient.jpg" />
</Frame>

Event-driven serverless processing

An event-driven pattern removes manual steps by automatically running compute when an event occurs. In this lesson we use AWS Lambda together with Amazon Bedrock to process new objects as they arrive.

AWS Lambda is a managed, ephemeral compute environment that runs your code in response to events. Typical invocations are short (seconds), and Lambda scales automatically to match load, making it ideal for per-event processing. From inside Lambda you can use the AWS SDKs to call other AWS services—Amazon Bedrock included—without embedding static credentials.

Typical workflow (S3 → Lambda → Bedrock → S3)

1. A file or object is uploaded to Amazon S3.
2. S3 emits an "Object Created" event.
3. The event triggers a Lambda function via S3 Event Notification.
4. The Lambda handler parses the event, reads the object, and constructs a Bedrock input (prompt).
5. Lambda invokes the Bedrock runtime to run a model (summarization, Q\&A, sentiment, etc.).
6. The model response is saved back to S3 for downstream use.

Visual summary of the flow:

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/tJmUiudNjsCWp_bm/images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/bedrock-lambda-s3-python-workflow.jpg?fit=max&auto=format&n=tJmUiudNjsCWp_bm&q=85&s=9d2d14389d500cd7dfca2e4e203903df" alt="A four-step flow diagram titled &#x22;Workflow: Use Bedrock With Lambda&#x22; showing: file uploaded to Amazon S3 → AWS Lambda runs Python code → AI model processing by Amazon Bedrock → save generated response back to S3." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/bedrock-lambda-s3-python-workflow.jpg" />
</Frame>

How S3 event notifications work

Amazon S3 supports Event Notifications for buckets. You can configure notifications on events such as "ObjectCreated" and optionally filter by prefix or suffix to limit which objects trigger the event. S3 then delivers an event record to a destination such as Lambda, SNS, or SQS.

In this lesson we configure S3 to send all "Object Created" events to a Lambda function (no prefix/suffix filters), so any object creation in the bucket will trigger the function.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/4OlDw81IoiRnJTCQ/images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-object-created-lambda-workflow.jpg?fit=max&auto=format&n=4OlDw81IoiRnJTCQ&q=85&s=1f950779ed3d23fd7a772cae5b90fad4" alt="A presentation slide titled &#x22;Workflow: S3 Events and Lambda&#x22; showing an AWS S3 &#x22;Create event notification&#x22; configuration screen. The caption explains that the &#x22;Object Created&#x22; event triggers on an S3 bucket to detect new file uploads, optionally filtered by prefix or suffix." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-object-created-lambda-workflow.jpg" />
</Frame>

Selecting the destination: Lambda

When creating the S3 event subscription you must choose a destination. Select the intended Lambda function (for example, `bedrock-summarize`). Every new object that matches the notification pattern will be delivered to that Lambda function for processing.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/tJmUiudNjsCWp_bm/images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-events-lambda-workflow.jpg?fit=max&auto=format&n=tJmUiudNjsCWp_bm&q=85&s=91de67f48f5b662b0b8093aa86553342" alt="A slide titled &#x22;Workflow: S3 Events and Lambda&#x22; showing an AWS console screenshot where an S3 event destination is configured to trigger a Lambda function (selected: &#x22;bedrock-summarize&#x22;). Below is a caption about linking the S3 bucket event directly to the target Lambda to create an automated event-driven connection." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-events-lambda-workflow.jpg" />
</Frame>

Inside the Lambda function

A Lambda function has an entry point called the handler. When S3 invokes Lambda, the handler receives an `event` parameter: a JSON payload describing what caused the invocation (including the S3 bucket and object key). Typical handler logic:

* Parse the event to extract S3 bucket and object key.
* Read the object from S3 and build the Bedrock prompt or input.
* Call the Bedrock runtime to run a model.
* Persist the model output back to S3 (or another storage destination).

Example Python Lambda handler that implements those steps:

```python theme={null}
# lambda_function.py
import json
import boto3

s3 = boto3.client("s3")
bedrock = boto3.client("bedrock-runtime")  # Bedrock runtime client

MODEL_ID = "your-model-id-or-name"  # Replace with your model identifier

def lambda_handler(event, context):
    # S3 event can contain multiple Records
    for record in event.get("Records", []):
        bucket = record["s3"]["bucket"]["name"]
        key = record["s3"]["object"]["key"]

        # Read the uploaded object
        obj = s3.get_object(Bucket=bucket, Key=key)
        body_bytes = obj["Body"].read()
        text_input = body_bytes.decode("utf-8")

        # Prepare and call Bedrock to process the text
        response = bedrock.invoke_model(
            modelId=MODEL_ID,
            contentType="text/plain",
            accept="application/json",
            body=text_input.encode("utf-8")
        )

        # Read model output from the streaming body
        model_output = response["body"].read().decode("utf-8")

        # Save the generated response back to S3 (e.g., in an outputs/ folder)
        output_key = f"outputs/{key}.json"
        s3.put_object(Bucket=bucket, Key=output_key, Body=model_output.encode("utf-8"))

    return {"status": "processed", "records": len(event.get("Records", []))}
```

Example S3 event payload (sent to Lambda):

```json theme={null}
{
  "Records": [
    {
      "eventName": "ObjectCreated:Put",
      "s3": {
        "bucket": { "name": "example-bucket" },
        "object": { "key": "uploads/document1.txt" }
      }
    }
  ]
}
```

Permissions and IAM roles

Lambda functions assume an IAM execution role that grants the permissions they need. Instead of embedding credentials in your code, attach a role with minimal privileges for the function to operate.

Common permissions to grant the Lambda execution role:

| Action | Purpose | Example IAM permission |
| - | - | - |
| Read source objects | Download newly uploaded objects from the source bucket | `s3:GetObject` |
| Write outputs | Save generated responses to a destination bucket or prefix | `s3:PutObject` |
| Call Bedrock | Allow the function to invoke the Bedrock runtime API | `bedrock:InvokeModel` |
| (optional) CloudWatch Logs | Enable logging for debugging and observability | `logs:CreateLogGroup`, `logs:CreateLogStream`, `logs:PutLogEvents` |

Use least-privilege policies and restrict the role to specific buckets and prefixes where possible.

<Callout icon="lightbulb" color="#1CB2FE">
  Use the Lambda execution role for all service access. Avoid embedding AWS credentials in your function code. For configuration values (model ID, output prefix, etc.), prefer Lambda environment variables or AWS Systems Manager Parameter Store / Secrets Manager.
</Callout>

Lambda console and function configuration

In the Lambda console you choose:

* Runtime (Python, Node.js, etc.).
* Handler name (the entry point function).
* Memory and timeout settings (default timeout is 3 seconds; configure up to 15 minutes if required).
* Execution role (attach the IAM role discussed above).
* Optionally, environment variables and layers.

When an S3 event triggers the function, Lambda injects the event JSON into your handler so your code can process it immediately.

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/tJmUiudNjsCWp_bm/images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-events-lambda-bedrock-summarize.jpg?fit=max&auto=format&n=tJmUiudNjsCWp_bm&q=85&s=07a149971d4a5bd217fece9d84aaf120" alt="A presentation slide titled &#x22;Workflow: S3 Events and Lambda&#x22; showing an AWS Lambda console screenshot for a function named &#x22;bedrock-summarize&#x22; with code in an editor, plus a caption describing using the Lambda to read S3 uploads and send them to Amazon Bedrock for processing." width="1920" height="1080" data-path="images/Introduction-to-Amazon-Bedrock/Integrating-Amazon-Bedrock-With-Other-AWS-Services/Exposing-Your-Bedrock-App-Using-API-Gateway-Part-1/s3-events-lambda-bedrock-summarize.jpg" />
</Frame>

Expected results and business benefits

This serverless pattern yields clear operational and business advantages:

| Benefit | Description |
| - | - |
| Real-time processing | Trigger AI workflows immediately on data arrival instead of batch windows. |
| Scalability | Lambda auto-scales to handle spikes; no need to provision servers. |
| Cost efficiency | Pay only for execution time when events occur. |
| Modularity | Small Lambda functions can focus on single responsibilities (summarize, sentiment, index). |
| Integration | Same pattern works with other AWS event sources (API Gateway, SQS, SNS, DynamoDB Streams, etc.). |

This pattern is flexible: substitute S3 with other event sources (SNS, SQS messages, DynamoDB streams), and adapt model calls to use classification, summarization, or generation as required.

Security and operational considerations

* Monitor execution times and error counts in CloudWatch. Configure retries and dead-letter queues (DLQ) for failed events.
* Use IAM policies scoped to required resources and restrict Bedrock access to necessary models.
* If model responses contain PII, ensure proper encryption at rest and access controls for output storage.
* For heavy workloads or long-running tasks, consider asynchronous patterns (queueing with SQS + FIFO) to smooth spikes.

<Callout icon="warning" color="#FF6B6B">
  Make sure your Lambda role has explicit permissions for Bedrock and S3 operations. Missing permissions cause invocation errors and retries. Also be mindful of regional endpoints for Bedrock—deploy and call Bedrock in the supported AWS regions for your account.
</Callout>

Key takeaway

Using Lambda with Amazon Bedrock enables automated, event-driven AI processing for incoming data. The S3 "object created" pattern is a common example, but the same architecture applies across many AWS event sources to deliver scalable, near-real-time generative AI workflows.

Next steps (hands-on lab)

1. Create an S3 bucket and enable "Object Created" event notifications.
2. Implement the Lambda handler (sample shown above) and set `MODEL_ID`.
3. Create an IAM execution role scoped to required S3 and Bedrock permissions.
4. Attach the role to the Lambda function and configure environment variables for model and output prefix.
5. Upload files to S3 and validate outputs appear in your `outputs/` prefix.
6. Monitor CloudWatch logs and refine error handling, concurrency limits, and retries.

Links and references

* [Amazon Bedrock Documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
* [AWS Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
* [S3 Event Notifications](https://docs.aws.amazon.com/AmazonS3/latest/userguide/NotificationHowTo.html)
* [IAM Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)

Good luck implementing your event-driven Bedrock workflows!

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/introduction-to-amazon-bedrock/module/6a77d10e-3172-4684-96bf-8e168372fae5/lesson/7d926bbf-9a9a-4ca4-8dcb-ea3c2f00e9f3" />
</CardGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.