Full-Stack AI with AWS Bedrock in Practice: The Code and Commands That Really Matter
Full Stack AI AWS Bedrock: The Essentials in One Article — Real Code, Diagrams and Concrete Steps, Excerpts from a 41-Lesson Course.
No endless theory here: we open the terminal and practice. Here is the essence of Full Stack AI AWS Bedrock, extracted directly from a complete 41-lesson course — with real code you can copy-paste right now.
- Create an AWS account and discover Bedrock
- Introduction to generative AI and AWS Bedrock
- Bedrock API and Python SDK Boto3
- Prompt Engineering for Bedrock
- FastAPI Backend with Bedrock
Install Boto3 and configure credentials
Learning objectives
What is Boto3?
Boto3 is the official Amazon Web Services SDK for Python. It lets you interact with all AWS services (S3, DynamoDB, Lambda, Bedrock, etc.) directly from Python code.
Boto3 – Low-level client
Direct access to AWS APIs. Each method corresponds exactly to a REST API operation. You work with Python dictionaries.
Boto3 – High-level resource
Object-oriented abstraction. More intuitive for certain services (S3, DynamoDB). For Bedrock we mainly use the client.
Step 1 – Install Python 3.8+
Boto3 requires Python 3.8 or higher. First check whether Python is already installed:
python --version
If the displayed version is 3.8+, proceed to the next step. Otherwise, install Python for your operating system:
Windows
Download the official installer from https://www.python.org/downloads/. Be sure to check the “Add Python to PATH” box during installation.
# Verification after installation python --version pip --version
macOS
# Via Homebrew (recommended) brew install python@3.11 # Verification python3 --version pip3 --version
Linux (Ubuntu / Debian)
sudo apt update sudo apt install python3 python3-pip python3-venv -y # Verification python3 --version pip3 --version
python3 and pip3 instead of python and pip, because python may point to Python 2.x on some systems.Step 2 – Create a virtual environment
A virtual environment isolates your project’s dependencies. It prevents conflicts between different Python projects on your machine.
Create and activate the venv
First call to Bedrock via the console
Learning objectives
1 – Access Amazon Bedrock
Step 1: Sign in to the AWS console
Open your browser and go to:
https://console.aws.amazon.com
Sign in with your AWS credentials. If you do not yet have an account, create one (AWS Free Tier gives you access to many services at no charge).
Step 2: Choose the correct region
Check the region in the top-right corner of the console:
+----------------------------------------------------------+ | AWS Console [N. Virginia v] | | ^^^^^^^^^^^^ | | Search bar : [ Amazon Bedrock ] | | | +----------------------------------------------------------+ If you see another region, click the dropdown menu and select “US East (N. Virginia)”.
Step 3: Find Amazon Bedrock
In the search bar at the top of the console, type “Bedrock” and click Amazon Bedrock in the results:
+----------------------------------------------------------+ | Search : [ Bedrock ] | | | | Results : | | +------------------------------------------------------+| | | Amazon Bedrock || | | Build with foundation models || | +------------------------------------------------------+| +----------------------------------------------------------+
You arrive on the Bedrock Dashboard.
2 – Enable model access
By default, no models are enabled. You must explicitly request access before you can use them.
Step 1: Go to Model access
In the left sidebar of Bedrock, click “Model access” (at the very bottom):
+----------------------------+------------------------------+ | Amazon Bedrock | | | | Bedrock Dashboard | | Playgrounds | | | Chat | Welcome to Amazon | | Text | Bedrock. Access | | Image | cutting-edge foundation | | | models via a single API. | | Orchestration | | | Agents | | | Knowledge bases | | | | | | Foundation models | | | Base models | | | Custom models | | | | | | Bedrock configurations | | | > Model access <-- | | +----------------------------+------------------------------+
Step 2: Request access
Click the “Manage model access” button (top right).
You will see the list of all available models. Check the following models for this course:
+----------------------------------------------------------+ | Manage model access | | | | Provider Model Access Status | | -------------------------------------------------------|| | [x] Anthropic Claude 3 Haiku Available || | [x] Anthropic Claude 3.5 Sonnet Available || | [ ] Anthropic Claude 3 Opus Available || | [x] Amazon Titan Text Express Available || | [x] Meta Llama 3 8B Instruct Available || | [x] Mistral AI Mistral 7B Instruct Available || | [x] Mistral AI Mixtral 8x7B Instruct Available || | | | [ Save changes ] | +----------------------------------------------------------+
Click “Save changes”. Access is usually granted within a few seconds.
Create a FastAPI + Bedrock API
Full Stack AI with AWS Bedrock • FastAPI Backend with Bedrock
/chat endpoint testable via Swagger UI, curl and PowerShell.What you will learn
1. Install dependencies
Make sure your virtual environment is activated, then install the libraries:
# Activate the virtual environment (Windows PowerShell) .\venv\Scripts\Activate.ps1 # Install the main libraries pip install fastapi uvicorn boto3 pydantic python-dotenv python-multipart
Verify that everything installed correctly:
pip list | findstr -i "fastapi uvicorn boto3"
You should see the three libraries with their version numbers.
2. Pydantic models
Pydantic lets you define the exact shape of the data your API accepts and returns. It is like a form with required fields: if the data does not match, the API automatically rejects the request with a clear error message.
# backend/models/schemas.py
from pydantic import BaseModel, Field
from typing import Optional, List
class Message(BaseModel):
"""Represents a message in the conversation."""
role: str = Field(
...,
description="Role: 'user' or 'assistant'",
examples=["user"]
)
content: str = Field(
...,
description="Message content",
examples=["Explain Python loops to me"]
)
class ChatRequest(BaseModel):
"""Request sent by the frontend to chat with the AI."""
message: str = Field(
...,
min_length=1,
max_length=10000,
description="User message"
)
history: Optional[List[Message]] = Field(
default=[],
description="Conversation history"
)
model_id: Optional[str] = Field(
default=None,
description="Bedrock model ID"
)
temperature: Optional[float] = Field(
default=0.7,
ge=0.0,
le=1.0,
description="Model creativity (0 = precise, 1 = creative)"
)
max_tokens: Optional[int] = Field(
default=4096,
ge=1,
le=8192,
description="Maximum number of tokens in the response"
)
class ChatResponse(BaseModel):
"""Response returned by the API after calling Bedrock."""
response: str = Field(
...,
description="Response generated by the AI"
)
model_id: str = Field(
...,
description="ID of the model used"
)
input_tokens: int = Field(
default=0,
description="Tokens consumed by the prompt"
)
output_tokens: int = Field(
default=0,
description="Tokens generated in the response"
)
class HealthResponse(BaseModel):
"""Health-check endpoint response."""
status: str
message: strIf the frontend sends a temperature value of 5.0 (outside the 0-1 range), Pydantic returns:
{
"detail": [
{
"loc": ["body", "temperature"],
"msg": "Input should be less than or equal to 1",
"type": "less_than_equal"
}
]
}3. The Bedrock service
The Bedrock service encapsulates all communication logic with AWS. This is where the “magic” happens: your text message is turned into an AWS request, sent to Claude, and the response is returned.
# backend/services/bedrock_service.py
import json
import boto3
from config import AWS_REGION, BEDROCK_MODEL_ID, MAX_TOKENS, TEMPERATURE
def get_bedrock_client():
"""Create and return a Bedrock Runtime client."""
return boto3.client(
service_name="bedrock-runtime",
region_name=AWS_REGION
)
def build_messages(message: str, history: list = None) -> list:
"""Build the list of messages for the Bedrock API."""
messages = []
if history:
for msg in history:
messages.append({
"role": msg.role,
"content": [{"type": "text", "text": msg.content}]
})
messages.append({
"role": "user",
"content": [{"type": "text", "text": message}]
})
return messages
def invoke_bedrock(
message: str,
history: list = None,
model_id: str = None,
temperature: float = None,
max_tokens: int = None
) -> dict:
"""
Call AWS Bedrock with the message and return the response.
Args:
message: The user message
history: The conversation history
model_id: The Bedrock model identifier
temperature: The creativity (0.0 to 1.0)
max_tokens: The maximum number of output tokens
Returns:
dict with the response, the model used and token counts
"""
client = get_bedrock_client()
model = model_id or BEDROCK_MODEL_ID
temp = temperature if temperature is not None else TEMPERATURE
tokens = max_tokens or MAX_TOKENS
messages = build_messages(message, history)
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": tokens,
"temperature": temp,
"messages": messages
})
response = client.invoke_model(
modelId=model,
contentType="application/json",
accept="application/json",
body=body
)
response_body = json.loads(response["body"].read())
return {
"response": response_body["content"][0]["text"],
"model_id": model,
"input_tokens": response_body.get("usage", {}).get(
"input_tokens", 0
),
"output_tokens": response_body.get("usage", {}).get(
"output_tokens", 0
),
}Body parameter details
| Parameter | Type | Description |
|---|---|---|
anthropic_version |
string | Anthropic API version used by Bedrock |
max_tokens |
int | Limits response length (1 token ≈ 0.75 word) |
temperature |
float | 0.0 = precise answers, 1.0 = creative answers |
messages |
list | The full conversation (history + new message) |
4. Complete main.py file
This is the application entry point. It assembles all components: configuration, CORS, routes and error handling.
# backend/main.py
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
from config import CORS_ORIGINS
from models.schemas import (
ChatRequest,
ChatResponse,
HealthResponse,
)
from services.bedrock_service import invoke_bedrock
load_dotenv()
app = FastAPI(
title="Full Stack AI - Backend Bedrock",
description="API to interact with AWS Bedrock (Claude)",
version="1.0.0",
)
# --- CORS Middleware ---
app.add_middleware(
CORSMiddleware,
allow_origins=CORS_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Endpoints ---
@app.get("/health", response_model=HealthResponse)
def health_check():
"""Check that the server is operational."""
return HealthResponse(
status="ok",
message="Server is running correctly"
)
@app.post("/chat", response_model=ChatResponse)
def chat(request: ChatRequest):
"""
Send a message to AWS Bedrock and return the AI response.
- **message** : text sent by the user
- **history** : conversation history (optional)
- **model_id** : Bedrock model to use (optional)
- **temperature** : creativity from 0.0 to 1.0 (optional)
- **max_tokens** : maximum number of output tokens (optional)
"""
try:
result = invoke_bedrock(
message=request.message,
history=request.history,
model_id=request.model_id,
temperature=request.temperature,
max_tokens=request.max_tokens,
)
return ChatResponse(**result)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Error calling Bedrock: {str(e)}"
)
@app.get("/models")
def list_models():
"""Return the list of available models."""
return {
"models": [
{
"id": "anthropic.claude-3-sonnet-20240229-v1:0",
"name": "Claude 3 Sonnet",
"description": "Good performance/cost balance"
},
{
"id": "anthropic.claude-3-haiku-20240307-v1:0",
"name": "Claude 3 Haiku",
"description": "Fastest and most economical"
},
{
"id": "anthropic.claude-3-5-sonnet-20240620-v1:0",
"name": "Claude 3.5 Sonnet",
"description": "Highest performance"
},
]
}This article covers the most useful excerpts — the complete Full Stack AI AWS Bedrock course (12 chapters, 41 lessons, corrected exercises and final project) takes you all the way.
./access-the-complete-course free course: Mastering Claude CodeFAQ
How long does it take to learn Full Stack AI AWS Bedrock?
Are there any prerequisites?
Where to start concretely?
📬 Want to receive this kind of guide every week? Subscribe for free — real code, zero fluff.