AWS Builder Center
Build a Serverless AI Application with AWS Lambda and Amazon Bedrock

Build a Serverless AI Application with AWS Lambda and Amazon Bedrock

Generative AI is becoming part of many modern applications, but building an AI-powered application doesn't always mean managing complicated infrastructure. In this tutorial, we’ll combine two AWS services to build a simple AI application: AWS Lambda — runs our application code without managing servers. Amazon Bedrock — gives our application access to foundation models through APIs. Our goal is simple: send a question to an API and receive an AI-generated answer.

🧠 What Are We Building?

We are going to build a simple AI API.
A user sends a question such as:
1
Explain cloud computing in simple words.
Our application will process the request and return an AI-generated response.
The architecture looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
User
│
▼
Amazon API Gateway
│
▼
AWS Lambda
│
▼
Amazon Bedrock
│
▼
Foundation Model
│
▼
AI-generated answer
This is a simple example, but the same architecture can be extended into chatbots, AI assistants, content-generation tools, document-processing systems, and many other applications.

☁️ What is AWS Lambda?

AWS Lambda is a serverless compute service that lets you run code without managing servers.
Instead of creating a server and keeping it running, you create a Lambda function and AWS runs it when it is invoked.
For example:
1
2
3
4
5
6
7
Request
↓
Lambda starts
↓
Your code runs
↓
Response
Lambda is especially useful for event-driven applications and APIs.
In our project, Lambda will receive the user's question and send it to Amazon Bedrock.

🤖 What is Amazon Bedrock?

Amazon Bedrock is an AWS service that provides access to foundation models through APIs.
Instead of building and hosting a large AI model yourself, you can use supported models through Bedrock.
This allows developers to focus on building their applications rather than managing the underlying model infrastructure.
For this tutorial, we will use the Amazon Bedrock Runtime API to send a prompt to a model and receive its response.
AWS provides the Converse API as a unified interface for models that support it, which makes it easier to write applications that can work with different supported models.

🔗 How Lambda and Bedrock Work Together

Think of the two services as having different jobs.
Lambda is the application logic.
Bedrock is the AI engine.
The flow is:
1
2
3
4
5
6
7
8
9
10
11
12
13
User asks a question
↓
API Gateway receives the request
↓
Lambda processes the request
↓
Lambda sends the prompt to Bedrock
↓
Bedrock runs the selected model
↓
AI response is returned to Lambda
↓
Lambda sends the response to the user
This separation makes the application easier to extend later.

🛠️ Step 1: Create a Lambda Function

Open the AWS Management Console and search for AWS Lambda.
Choose:
Create function → Author from scratch
Give the function a name such as:
1
serverless-ai-api
Choose Python as the runtime.
Then create the function.
Once the function is created, we can add our application code.

🔐 Step 2: Give Lambda Permission to Use Bedrock

Our Lambda function needs permission to call Amazon Bedrock.
Lambda uses an execution role to determine which AWS resources and APIs the function can access.
Open the Lambda function's execution role in IAM and add a policy that allows the required Bedrock inference action.
For a learning project, the permission might look similar to:
1
2
3
4
5
6
7
8
9
10
11
12
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel"
],
"Resource": "*"
}
]
}
For production applications, permissions should be restricted as much as practical instead of automatically granting broad access.
The important idea is:
Lambda needs permission to call Bedrock.
Without this permission, the function may fail when it tries to generate an AI response.

💻 Step 3: Write the Lambda Code

Now let's write our Python function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import json
import os
import boto3

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

MODEL_ID = os.environ["MODEL_ID"]

def lambda_handler(event, context):

body = json.loads(event.get("body", "{}"))

prompt = body.get("prompt")

if not prompt:
return {
"statusCode": 400,
"body": json.dumps({
"error": "Please provide a prompt"
})
}

response = bedrock.converse(
modelId=MODEL_ID,
messages=[
{
"role": "user",
"content": [
{
"text": prompt
}
]
}
],
inferenceConfig={
"maxTokens": 300,
"temperature": 0.5
}
)

answer = response["output"]["message"]["content"][0]["text"]

return {
"statusCode": 200,
"body": json.dumps({
"answer": answer
})
}
Don't worry if the code looks a little long.
Let's break it down.

🔍 Understanding the Code

1. Import the libraries

1
2
3
import json
import os
import boto3
We use:
  • json to work with JSON requests and responses.
  • os to read environment variables.
  • boto3 to communicate with AWS services.

2. Create a Bedrock client

1
bedrock = boto3.client("bedrock-runtime")
This creates a client that allows our Lambda function to communicate with the Amazon Bedrock Runtime service.

3. Get the model ID

1
MODEL_ID = os.environ["MODEL_ID"]
Instead of hard-coding the model ID inside our code, we store it as an environment variable.
This makes it easier to change the model later without rewriting the application code.

4. Read the user's prompt

1
2
3
body = json.loads(event.get("body", "{}"))

prompt = body.get("prompt")
Our API expects a request like:
1
2
3
{
"prompt": "Explain artificial intelligence in simple words."
}
Lambda reads the prompt from the request.

5. Send the prompt to Bedrock

This is the most important part:
1
2
3
4
5
6
7
8
9
10
11
12
13
response = bedrock.converse(
modelId=MODEL_ID,
messages=[
{
"role": "user",
"content": [
{
"text": prompt
}
]
}
]
)
Our Lambda function sends the user's prompt to the selected model through the Bedrock Converse API.

6. Get the AI response

1
answer = response["output"]["message"]["content"][0]["text"]
The generated text is extracted from the Bedrock response.
We then return it to the user.

⚙️ Step 4: Configure the Model ID

In your Lambda function, open:
Configuration → Environment variables
Add:
1
2
Key: MODEL_ID
Value: YOUR_SUPPORTED_MODEL_ID
Choose a model that is available to your AWS account and region.
This is useful because model availability and access can vary by region and account.

🧪 Step 5: Test the Lambda Function

Let's test our function before connecting it to an API.
Create a test event with:
1
2
3
{
"body": "{\"prompt\":\"Explain cloud computing in simple words.\"}"
}
Run the test.
If everything is configured correctly, Lambda should return something similar to:
1
2
3
4
{
"statusCode": 200,
"body": "{\"answer\":\"Cloud computing means using computing resources such as servers and storage over the internet instead of managing them yourself.\"}"
}
The exact response will vary because it is generated by the AI model.
🎉 Our serverless AI backend is working!

🌐 Step 6: Connect API Gateway

Right now, we can invoke Lambda from AWS.
But we want users or applications to be able to send HTTP requests.
That's where Amazon API Gateway comes in.
Our architecture becomes:
1
2
3
4
5
6
7
8
9
10
11
12
13
Client
│
▼
API Gateway
│
▼
Lambda
│
▼
Amazon Bedrock
│
▼
AI Model
Create an HTTP API in API Gateway and connect it to our Lambda function.
Create a route such as:
1
POST /ask
After deploying the API, API Gateway will provide an endpoint.

🚀 Step 7: Send Our First AI Request

Now we can send a POST request to our API.
For example:
1
2
3
{
"prompt": "What is machine learning?"
}
The request travels through our entire application:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
POST /ask
↓
API Gateway
↓
Lambda
↓
Amazon Bedrock
↓
AI Model
↓
Lambda
↓
API Gateway
↓
Client
The client receives the AI-generated answer.
We have now built a serverless AI API.

💡 Why This Architecture Is Useful

This small project demonstrates an important pattern:
API Gateway + Lambda + Bedrock
Each service has a clear responsibility.

API Gateway

Handles HTTP requests.

Lambda

Runs our application logic.

Bedrock

Handles AI inference.
Because these components are separated, we can replace or extend individual parts later.
For example, we could add a database:
1
2
3
4
5
API Gateway
↓
Lambda
↙ ↘
DynamoDB Bedrock
Now our application could store conversations while still using Bedrock for AI responses.

🌎 Real-World Applications

The same architecture can be used to build:

💬 AI Chatbots

Create a chatbot that answers questions from users.

📚 AI Study Assistant

Students can ask questions and receive explanations.

📝 Content Assistant

Generate summaries, descriptions, or drafts.

🏢 Customer Support

Create an AI-powered support system.

📄 Document Processing

Process information extracted from documents and generate useful responses.

🤖 AI Agents

Combine models with tools, APIs, databases, and business logic to create more capable AI applications.

🔒 Important Security Practices

When building AI applications, security should be considered from the beginning.

Don't expose AWS credentials

Your application should use IAM roles rather than placing AWS access keys inside your source code.

Validate user input

Don't blindly trust data coming from an API request.

Use least-privilege permissions

Give your Lambda execution role only the permissions it needs.

Protect your API

For a real application, don't leave an AI endpoint completely open to everyone. Consider authentication, authorization, throttling, and other API protections.

Monitor your application

Use Amazon CloudWatch to monitor Lambda executions, logs, errors, and performance.

🚀 Take It Further

Our application is intentionally simple.
Now you can start adding more features.
Try adding:
1
2
3
4
5
6
7
┌── DynamoDB
│
User → API Gateway → Lambda → Bedrock
│
├── S3
│
└── Authentication
You could build:
  • A complete AI chatbot
  • A document Q&A application
  • An AI study assistant
  • An AI customer-support system
  • A serverless RAG application
  • An AI-powered web application

🎯 What We Learned

In this tutorial, we:
  • Learned what AWS Lambda does
  • Learned what Amazon Bedrock provides
  • Created a Lambda function
  • Gave Lambda permission to call Bedrock
  • Used the Bedrock Converse API
  • Sent a prompt to an AI model
  • Returned the AI response
  • Connected Lambda to API Gateway
  • Built a serverless AI API
The important idea is simple:
Lambda handles the application logic, while Amazon Bedrock handles the AI.
You don't need to build and host an AI model from scratch to start creating AI-powered applications.
Start small, understand the architecture, and then keep adding features.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article