> ## 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 2

> Guide for routing API Gateway requests to AWS Lambda that call Amazon Bedrock foundation models, covering integration patterns, routing behavior, security, and practical tips for secure serverless generative APIs

This guide explains how to route requests from Amazon API Gateway to AWS Lambda functions that call Amazon Bedrock foundation models. It covers routing behavior, integration patterns, and practical tips for building a secure, maintainable serverless API that exposes generative AI capabilities.

## How API Gateway routing works

When you create a custom REST API in API Gateway you receive an execute-api endpoint such as:

```http theme={null}
https://abc1234.execute-api.us-east-1.amazonaws.com/preprod
```

Inside the API you define resources and HTTP methods. For example, if you add `summarize` and `sentiment` resources, their full endpoints become:

```http theme={null}
GET https://abc1234.execute-api.us-east-1.amazonaws.com/preprod/summarize
GET https://abc1234.execute-api.us-east-1.amazonaws.com/preprod/sentiment
```

API Gateway does not run your business logic. Instead it routes requests to configured integrations — commonly Lambda functions, HTTP endpoints, or other AWS services. For each resource you choose which HTTP verbs it supports (GET, POST, PUT, DELETE, PATCH, OPTIONS, etc.) and which integration handles those verbs.

## Example pattern: one Lambda per resource/method

In this example both `summarize` and `sentiment` implement the GET method and each is mapped to a dedicated Lambda function:

* Summarize Lambda: constructs a prompt and calls a Bedrock foundation model to produce a concise summary.
* Sentiment Lambda: constructs a prompt and calls a Bedrock foundation model to return sentiment (positive / negative / neutral).

Using separate Lambda functions creates a simple one-to-one mapping between API routes and code, reducing deployment blast radius and simplifying permissions.

Example request flow:

1. Client calls API Gateway endpoint.
2. API Gateway routes the request to the configured Lambda.
3. Lambda constructs a prompt, calls Bedrock, and returns the model response.
4. API Gateway returns the response to the client.

Below is a compact Lambda example (Python) showing the typical shape of the handler that creates a client and calls Bedrock. This is illustrative — adapt to your model invocation patterns and SDK usage.

```python theme={null}
import json
import os
import boto3

bedrock = boto3.client("bedrock-runtime")  # service name may vary by SDK version

MODEL_ID = os.environ.get("MODEL_ID", "my-foundation-model")

def lambda_handler(event, context):
    # Extract input from query string or mapped body
    text = event.get("queryStringParameters", {}).get("text", "") or json.loads(event.get("body", "{}")).get("text", "")
    prompt = f"Summarize this text:\n\n{text}"

    response = bedrock.invoke_model(
        modelId=MODEL_ID,
        contentType="application/json",
        accept="application/json",
        body=json.dumps({"prompt": prompt, "maxTokens": 200})
    )

    model_output = json.loads(response["body"])  # adjust parsing to the model's response shape

    return {
        "statusCode": 200,
        "headers": {"Content-Type": "application/json"},
        "body": json.dumps({"summary": model_output.get("output", "")})
    }
```

<Callout icon="lightbulb" color="#1CB2FE">
  When deciding between multiple Lambdas vs. a single Lambda with internal routing, favor multiple Lambdas for clearer separation of concerns and smaller, safer deployments. Use a single Lambda only if you need a consolidated codebase and are willing to add internal routing logic.
</Callout>

## Event-driven vs API-based on-demand

The two common architectural patterns for invoking Bedrock are:

* Event-driven (asynchronous): Infrastructure events (for example, S3 object-created notifications) trigger a Lambda that reads the object, builds a prompt, calls Bedrock, and stores or forwards the result.
* API-based on-demand (synchronous): A user or client calls an API Gateway endpoint; API Gateway routes the request to Lambda, which calls Bedrock and returns the response to the client.

<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-2/bedrock-event-driven-and-api-workflow.jpg?fit=max&auto=format&n=4OlDw81IoiRnJTCQ&q=85&s=313b1a05ccb72573a150416c5f994c8a" alt="A side-by-side workflow diagram titled &#x22;Workflow: Bedrock in Event-Driven Architecture&#x22; showing two processing paths: an event-driven file upload flow (File Upload → S3 Bucket → Lambda → Amazon Bedrock → Response) and an API-based on-demand flow (User Request → API Gateway → Lambda → Amazon Bedrock → Response). Both pipelines feed into Amazon Bedrock and return a response." 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-2/bedrock-event-driven-and-api-workflow.jpg" />
</Frame>

Comparing the patterns:

| Pattern | Trigger | Typical use cases | Response model |
| -: | :- | :- | :- |
| Event-driven | S3 events, SQS, SNS, etc. | Batch processing, pipelines, background jobs | Asynchronous (result stored or delivered later) |
| API-based on-demand | HTTP requests via API Gateway | Interactive apps, web/mobile clients, real-time tools | Synchronous (client waits for result) |

Both patterns ultimately call Bedrock, but they differ in latency expectations, error handling, and operational considerations.

## Benefits of exposing Bedrock via API Gateway + Lambda

* Faster integration into existing systems: Consumers call a single REST API to access generative features.
* Reuse: Front ends, mobile apps, and third-party services share the same backend logic.
* Lower maintenance overhead: Fixes and model tuning happen server-side and benefit all clients.
* Interface flexibility: Expose simple REST routes (summarize, sentiment, classify) while encapsulating model details.

<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-2/results-ai-integration-realtime-api-production.jpg?fit=max&auto=format&n=4OlDw81IoiRnJTCQ&q=85&s=ed5e0c77b4c5c0ecb9521660e8188764" alt="A slide titled &#x22;Results&#x22; shows an illustration of a laptop with code, a small building icon, and a person using a laptop. To the right are stacked green boxes summarizing AI outcomes like integration into broader systems, powering real-time tools, reuse via a single API, and a shift to production-ready applications." 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-2/results-ai-integration-realtime-api-production.jpg" />
</Frame>

## Key implementation notes (practical tips)

* Use structured request and response schemas (JSON) so clients know the expected payload shape.
* Choose the right API Gateway integration:
  * Lambda proxy integration forwards the full HTTP request to Lambda (headers, path, query string, body) — implement parsing in Lambda.
  * Mapped integration lets API Gateway transform requests/responses before they reach the Lambda.
* Keep configuration and secrets out of client code. Use Lambda environment variables, AWS Secrets Manager, or a configuration service for model IDs and sensitive parameters.
* Monitor costs and latency. Foundation models can vary in performance and cost — track usage with Amazon CloudWatch and use AWS X-Ray to trace end-to-end latency.
* Implement retries and graceful error handling in Lambda to handle transient model invocation failures.
* Secure your API Gateway endpoints with authentication and authorization: API keys, IAM, Amazon Cognito, or custom authorizers.

<Callout icon="warning" color="#FF6B6B">
  Protect your generative endpoints. Enforce authentication/authorization, validate and sanitize inputs to reduce prompt injection risks, and limit the rate of requests to control costs.
</Callout>

## Quick checklist before production

* Define clear input/output JSON contracts for each route.
* Store model identifiers and invocation parameters in a secure configuration store.
* Apply least-privilege IAM roles to Lambdas and API Gateway.
* Set up CloudWatch alarms and X-Ray tracing for observability.
* Add request throttling and quotas in API Gateway to avoid runaway costs.

## Takeaway

Using API Gateway and Lambda to expose Amazon Bedrock capabilities gives you a familiar, scalable pattern for adding generative AI to applications. The API acts as the stable contract for clients, while Lambda centralizes prompt construction, model selection, and response handling. This approach simplifies integration, promotes reuse, and reduces the client-side complexity of working directly with foundation models.

This completes the short introduction to using Amazon API Gateway with Lambda to call Amazon Bedrock. You can combine Bedrock with Amazon Lex or other AWS services to build conversational or hybrid generative experiences.

## Links and references

* [Amazon API Gateway documentation](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html)
* [AWS Lambda documentation](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
* [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
* [Amazon S3 documentation](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)
* [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)
* [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)
* [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html)
* [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)

<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/ee524c26-23fd-4a37-9d69-d9933f086442" />
</CardGroup>


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