Skip to content
AWS

A Chatbot API with Lambda, API Gateway and Bedrock, Deployed with CDK

The smallest useful serverless AI app: an HTTP endpoint that sends a message to Amazon Bedrock and returns the reply, with a rate limit and a token check

In the last post I called a model from the console, the CLI and Python. That works for me at a terminal, but nothing else can use it. This post puts the call behind an HTTP endpoint, so anything that can send a web request can talk to the model. It is the smallest useful serverless AI app, and the later posts in this series build on it.

What We Are Building

One request in, one reply out:

Diagram of the chatbot API. A client sends an HTTPS POST to API Gateway, which invokes a Lambda function. The function calls Amazon Bedrock (Nova Micro) with the Converse API and writes token counts and errors to CloudWatch Logs. API Gateway, the function, Bedrock and the logs all sit inside the eu-west-2 Region.

  • An HTTP API in API Gateway with a rate limit on it
  • A Lambda function in Python that checks a shared token, validates the message and calls Bedrock with the Converse API
  • An IAM role that lets that function call one model and nothing else
  • All of it defined in code with the AWS CDK, so it deploys with one command and disappears with one command

I am using the CDK rather than SAM because it was already installed on my Mac, and because the Python version reads almost like the diagram above.

Before We Start

  • The sandbox account and sandbox profile from the sandbox post, signed in with aws sso login --profile sandbox. This post needs one extra permission, covered in “Widen the Sandbox Permissions” below
  • The same Region as the rest of the series, eu-west-2, and the same model, Nova Micro, from the first call post
  • The AWS CDK CLI (cdk --version should print a version). It needs Node.js, and it is installed with npm install -g aws-cdk
  • Python 3 and uv, or the built-in venv module if you prefer

A Word on Security First

An endpoint on the internet that calls a paid service is a bill waiting to happen if anyone finds the URL. Two cheap protections go in from the start, and I think they belong in a first version rather than a later “hardening” post:

  1. A rate limit on the API itself, so even a leaked URL can only make a few requests per second
  2. A shared token that the function checks before it calls the model, plus a cap on message length and on the length of the reply

The shared token is a demo-only compromise. In this version it is stored as a plain environment variable on the function, so anyone who can read the function’s configuration can read the token, and it also ends up in the CloudFormation template that the CDK generates. That is acceptable in a sandbox account that only I can sign in to, for something I am about to delete. For a real application you would use something like Amazon Cognito, a Lambda authoriser, or at least keep the secret in AWS Secrets Manager. I come back to this at the end.

Widen the Sandbox Permissions

This is the build I said would need IAM. The PowerUserAccess permission set from the sandbox post deliberately blocks IAM, and two things here create IAM roles: the CDK bootstrap, and the Lambda function’s execution role. Without a change, bootstrap fails with errors like this:

text
... is not authorized to perform: iam:GetRole on resource: role cdk-hnb659fds-... because no identity-based policy allows the iam:GetRole action

The fix is to add one more AWS managed policy to the same permission set:

  1. Sign in to the management account as a user who can administer Identity Center. That is often a different identity from the sandbox user you use day to day. Open IAM Identity Center, then Permission sets, and open the one assigned to your sandbox (mine is PowerUserAccess, but use whatever you named it)
  2. Under Permissions policies, choose Attach managed policies and add IAMFullAccess
  3. The change is applied to the sandbox account, which is a different account from the one you are editing it in. If the console shows the account as out of date, choose Reprovision
  4. Give it a minute. If the next command still says AccessDenied, run aws sso login --profile sandbox again to get fresh credentials

PowerUserAccess plus IAMFullAccess is effectively administrator access inside this one account, apart from Organizations and account settings. IAM write access can also be used to give yourself more permissions, so this is a real step up. I am comfortable with it in a sandbox that only I can sign in to and that has a budget alert. I would not do it in an account that holds anything I care about. A tighter alternative is an inline policy or a permissions boundary limited to the roles this stack creates, but the CDK bootstrap roles and the generated Lambda role names make that fiddly, so I have not done it here.

Remember to take it back out. Later deploys and destroys in this series still need it, so detach IAMFullAccess from the permission set at the end, after the last cdk destroy.

If you already ran cdk bootstrap and it failed, it will have left a half-created CDKToolkit stack behind. Check it before you try again:

bash
aws cloudformation describe-stacks --stack-name CDKToolkit \
  --profile sandbox --region eu-west-2 \
  --query 'Stacks[0].StackStatus' --output text

What to do depends on what it prints:

  • The stack does not exist, or it prints CREATE_COMPLETE or UPDATE_COMPLETE: leave it alone. Either there is nothing to clean up, or the bootstrap already worked, and deleting a healthy stack would only make you redo it
  • ROLLBACK_IN_PROGRESS or DELETE_IN_PROGRESS: wait a minute and check again
  • ROLLBACK_COMPLETE: the normal failed-bootstrap case. Delete it and wait for the delete to finish, then run the bootstrap again
  • ROLLBACK_FAILED: delete it the same way, but this can end in DELETE_FAILED if a resource cannot be removed. If it does, open the stack in the CloudFormation console, choose Delete again, and tick the option to retain the resources that are stuck, then check for anything left behind by hand
bash
aws cloudformation delete-stack --stack-name CDKToolkit \
  --profile sandbox --region eu-west-2
aws cloudformation wait stack-delete-complete --stack-name CDKToolkit \
  --profile sandbox --region eu-west-2

Deleting this stack is only safe because this is a throwaway sandbox and the stack is the failed bootstrap. Do not copy that habit into an account that has working CDK projects in it.

Create the Project

bash
mkdir chatbot-api
cd chatbot-api
uv venv
source .venv/bin/activate
mkdir lambda

Create requirements.txt. I built this with aws-cdk-lib 2.278.0, so I have put that as the minimum:

text
aws-cdk-lib>=2.278.0
constructs>=10.0.0,<11.0.0

Install it, and add a .gitignore so the generated cdk.out folder (which contains your token in plain text) and the virtual environment never get committed:

bash
uv pip install -r requirements.txt
printf '.venv/\ncdk.out/\n__pycache__/\n' > .gitignore

Without uv, the equivalent is python3 -m venv .venv, source .venv/bin/activate and pip install -r requirements.txt. Keep the virtual environment active for every cdk command in this post, because the CDK runs app.py with whichever python3 it finds.

Create cdk.json, which tells the CDK how to run the app:

json
{
  "app": "python3 app.py"
}

Create app.py:

python
#!/usr/bin/env python3
import aws_cdk as cdk

from chatbot_stack import ChatbotStack

app = cdk.App()
ChatbotStack(
    app,
    "ChatbotApi",
    env=cdk.Environment(region="eu-west-2"),
)
app.synth()

The Lambda Function

Save this as lambda/handler.py. The order matters: it checks the token and validates the input before it does anything that costs money.

python
import hmac
import json
import os

import boto3
from botocore.exceptions import ClientError

MODEL_ID = os.environ["MODEL_ID"]
API_TOKEN = os.environ["API_TOKEN"]
MAX_INPUT_CHARS = 1000

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


def respond(status, body):
    return {
        "statusCode": status,
        "headers": {"content-type": "application/json"},
        "body": json.dumps(body),
    }


def lambda_handler(event, context):
    headers = event.get("headers") or {}
    token = headers.get("x-api-token", "")
    if not hmac.compare_digest(token.encode(), API_TOKEN.encode()):
        return respond(401, {"error": "unauthorised"})

    try:
        message = json.loads(event.get("body") or "{}")["message"]
    except (json.JSONDecodeError, KeyError, TypeError):
        return respond(400, {"error": "send JSON like {\"message\": \"hello\"}"})

    if not isinstance(message, str) or not message.strip():
        return respond(400, {"error": "message must be a non-empty string"})
    if len(message) > MAX_INPUT_CHARS:
        return respond(400, {"error": f"message is over {MAX_INPUT_CHARS} characters"})

    try:
        response = client.converse(
            modelId=MODEL_ID,
            system=[{"text": "You are a concise, friendly assistant. Keep answers under 100 words."}],
            messages=[{"role": "user", "content": [{"text": message}]}],
            inferenceConfig={"maxTokens": 300, "temperature": 0.3},
        )
    except ClientError as err:
        # The full error goes to CloudWatch Logs; the caller gets a generic message.
        print(json.dumps({"bedrockError": err.response["Error"]["Code"], "detail": str(err)}))
        return respond(502, {"error": "the model call failed, check the function logs"})

    usage = response["usage"]
    print(json.dumps({"inputTokens": usage["inputTokens"], "outputTokens": usage["outputTokens"]}))

    return respond(
        200,
        {
            "reply": response["output"]["message"]["content"][0]["text"],
            "usage": {
                "inputTokens": usage["inputTokens"],
                "outputTokens": usage["outputTokens"],
            },
        },
    )

A few things worth pointing out:

  • It is the same converse call as last time, now inside a handler. Changing model later is a change to one environment variable.
  • API Gateway HTTP APIs lower-case the header names they pass to Lambda, which is why the code looks for x-api-token in lower case.
  • The token is compared with hmac.compare_digest rather than !=, which takes the same time whether or not the first characters match. It is a small habit worth having for any secret comparison.
  • If Bedrock returns an error (throttling, access denied, or the “account is being verified” message from the last post), the function logs the full error to CloudWatch and returns a plain 502 to the caller. Without that, you would get a bare 500 and no clue why.
  • maxTokens limits how much the model can write back, which limits the cost of each call.
  • The print line writes the token counts to CloudWatch Logs. That gives us a record of usage per request, which matters when we look at cost control later in the series.

The Infrastructure

Save this as chatbot_stack.py:

python
from aws_cdk import (
    CfnOutput,
    Duration,
    RemovalPolicy,
    Stack,
    aws_apigatewayv2 as apigw,
    aws_iam as iam,
    aws_lambda as _lambda,
    aws_logs as logs,
)
from aws_cdk.aws_apigatewayv2_integrations import HttpLambdaIntegration
from constructs import Construct

DEFAULT_MODEL_ID = "amazon.nova-micro-v1:0"


class ChatbotStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Shared secret, passed in at deploy time: cdk deploy -c api_token=...
        api_token = self.node.try_get_context("api_token")
        if not api_token:
            raise ValueError("Pass a token: cdk deploy -c api_token=<value>")

        # Optional: -c model_id=eu.amazon.nova-micro-v1:0 to use the EU inference profile.
        model_id = self.node.try_get_context("model_id") or DEFAULT_MODEL_ID
        base_model_id = model_id.removeprefix("eu.")

        fn = _lambda.Function(
            self,
            "ChatFunction",
            runtime=_lambda.Runtime.PYTHON_3_13,
            handler="handler.lambda_handler",
            code=_lambda.Code.from_asset("lambda"),
            timeout=Duration.seconds(20),
            memory_size=256,
            log_group=logs.LogGroup(
                self,
                "ChatLogs",
                retention=logs.RetentionDays.ONE_WEEK,
                removal_policy=RemovalPolicy.DESTROY,
            ),
            environment={
                "MODEL_ID": model_id,
                "API_TOKEN": api_token,
            },
        )

        # Allow this one function to call this one model, nothing else.
        fn.add_to_role_policy(
            iam.PolicyStatement(
                actions=["bedrock:InvokeModel"],
                resources=[
                    f"arn:aws:bedrock:*::foundation-model/{base_model_id}",
                    f"arn:aws:bedrock:*:{self.account}:inference-profile/eu.{base_model_id}",
                ],
            )
        )

        api = apigw.HttpApi(
            self,
            "ChatApi",
            default_integration=HttpLambdaIntegration("ChatIntegration", fn),
        )

        # Cap the request rate so a leaked URL cannot run up a bill.
        cfn_stage = api.default_stage.node.default_child
        cfn_stage.default_route_settings = apigw.CfnStage.RouteSettingsProperty(
            throttling_rate_limit=2,
            throttling_burst_limit=5,
        )

        CfnOutput(self, "ApiUrl", value=api.url or "")

The parts that matter:

  • The IAM policy allows bedrock:InvokeModel on Nova Micro only. The Converse API is authorised through that action. The first ARN has a * for the Region, so it allows that one model in any Region, which is what a cross-Region inference profile needs. The second ARN is the eu. inference profile in your account. self.account is the CDK’s placeholder for the account ID, which CloudFormation fills in at deploy time.
  • The model ID is one setting that drives both the environment variable and the policy. If the last post sent you to the eu.amazon.nova-micro-v1:0 profile ID, deploy with -c model_id=eu.amazon.nova-micro-v1:0 and both change together.
  • The throttle is two requests a second with a burst of five. That is plenty for me testing with curl, and low enough to put a ceiling on what anyone else can do.
  • The log group keeps logs for a week and is deleted with the stack, so nothing is left behind.
  • The token is passed in when you deploy, so it is not written in any file you create. It does appear in the generated cdk.out folder and in the function’s environment variables, as explained above, which is why the .gitignore matters.

Deploy It

The CDK needs some resources in the account before its first deployment, which it creates with a one-off bootstrap. Run it once per account and Region. I name the Region explicitly, because without it the CDK uses the profile’s default Region, which might not be eu-west-2:

bash
ACCOUNT_ID=$(aws sts get-caller-identity --profile sandbox --query Account --output text)
cdk bootstrap aws://$ACCOUNT_ID/eu-west-2 --profile sandbox -c api_token=unused

The -c api_token=unused looks odd, but it is needed. Every cdk command, including bootstrap, runs app.py first, and the stack refuses to build without a token. Bootstrap does not deploy the stack, so any value will do. If you leave it out you get ValueError: Pass a token.

Create a token. Then run cdk synth, which builds the template without deploying anything, and cdk diff, which shows what a deploy would change:

bash
export API_TOKEN=$(openssl rand -hex 16)
cdk synth --profile sandbox -c api_token=$API_TOKEN
cdk diff --profile sandbox -c api_token=$API_TOKEN

Then deploy:

bash
cdk deploy --profile sandbox -c api_token=$API_TOKEN

The CDK shows the IAM changes and asks you to approve them. Read them. Besides the Bedrock permission above, you will see the standard permissions that let Lambda write logs and let API Gateway call the function. What you are checking for is a * in the Resource column of anything that is not one of those. When it finishes, it prints an ApiUrl output.

Typing the token into the command line means it can show up in your shell history and in the process list while the command runs. That is fine for a throwaway token on my own Mac, but it is another reason this is a demo-only approach.

Look at It in the Console

Before calling it, look at what was built, because that is where you will go when something breaks:

  1. API Gateway: open the API and look at the $default route and the stage. Under the stage’s throttling settings you should see a rate of 2 and a burst of 5. You can check the same thing from the CLI by looking for DefaultRouteSettings in the output of aws apigatewayv2 get-stage --api-id <api id> --stage-name '$default' --profile sandbox --region eu-west-2
  2. Lambda: open the function and look at its Configuration tab. Under Permissions you will find the role and the Bedrock policy, and under Environment variables you will see API_TOKEN in plain text, as warned above
  3. CloudWatch Logs: the function’s log group is where the token counts and any Bedrock errors go. From the terminal, aws logs tail --follow --profile sandbox --region eu-west-2 <log group name> shows them as they happen

Try It

First put the API address in a variable. The deploy printed it as ApiUrl, and you can read it back from the stack at any time:

bash
API_URL=$(aws cloudformation describe-stacks --stack-name ChatbotApi \
  --profile sandbox --region eu-west-2 \
  --query "Stacks[0].Outputs[?OutputKey=='ApiUrl'].OutputValue" --output text)
echo $API_URL

It should print an address like https://abc123.execute-api.eu-west-2.amazonaws.com/. Then send a request:

bash
curl -X POST "$API_URL" \
  -H "content-type: application/json" \
  -H "x-api-token: $API_TOKEN" \
  -d '{"message": "In one sentence, what is a Lambda function?"}'

You should get back a JSON reply with the model’s answer and the token counts. Then check that the protections work:

bash
# No token: expect 401
curl -X POST "$API_URL" -H "content-type: application/json" -d '{"message": "hi"}'

# Empty message: expect 400
curl -X POST "$API_URL" -H "content-type: application/json" \
  -H "x-api-token: $API_TOKEN" -d '{"message": ""}'

If Bedrock refuses the call, you will get a 502 with a short message, and the real reason will be in the function’s log group.

What It Cost

Three services are involved, and all of them charge per use:

  • Bedrock charges per input and output token, as in the last post. Work it out from the usage numbers in your own replies, using the same sum as before.
  • Lambda charges per request and for the time the function runs. It has a monthly free tier, which you should check on the pricing page.
  • API Gateway charges per million requests for HTTP APIs.

I will not quote prices here because they change, so check the Bedrock, Lambda and API Gateway pricing pages for your Region.

The protections limit the damage rather than remove it. At two requests a second, the throttle allows roughly 170,000 requests a day. Requests without the token still start the Lambda function, which costs a little, but they stop before reaching Bedrock, which is where the real cost is. If the token itself leaked, Bedrock calls would be limited by the throttle and by the 300 token cap on each reply. The budget alert from the first post is the backstop, and I would still tear this down as soon as I have finished testing.

Cleaning Up

bash
cdk destroy --profile sandbox -c api_token=unused
unset API_TOKEN

The CDK needs a value for api_token to build the stack, but it is not used when deleting, so unused is fine, and it still works in a new terminal where $API_TOKEN no longer exists. That removes the API, the function, its role and the log group. The bootstrap resources from cdk bootstrap stay behind in the account, because the CDK uses them for every project. They cost next to nothing, and you would only remove them by deleting the CDKToolkit stack in CloudFormation, which is only worth doing if you are retiring the account.

The IAMFullAccess policy you added to the permission set is not part of this stack, so cdk destroy does not remove it. I keep it attached while I work through the series, and detach it when I finish the last build.

What I’d Do Next

  • Replace the shared token with real authentication. Cognito or a Lambda authoriser would let different users have different limits.
  • Add conversation history. This version has no memory, because each request is a single message.
  • Put it to work on my own writing, which is the next post: giving the model my blog posts to answer from, using Bedrock Knowledge Bases.