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.

Full-Stack AI with AWS Bedrock in Practice: The Code and Commands That Really Matter

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.

tl;dr
  • 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
~$ cat ./parcours.md # Full Stack AI AWS Bedrock — 11 chapters
01
Create an AWS account and discover Bedrock
→ Create an AWS Free Tier account→ Configure IAM and security+ 1 more lessons
02
Introduction to generative AI and AWS Bedrock
→ What is generative AI?→ Overview of foundation models+ 1 more lessons
03
Bedrock API and Python SDK Boto3
→ Install Boto3 and configure credentials→ Invoke models with Python+ 1 more lessons
04
Prompt Engineering for Bedrock
→ Principles of Prompt Engineering→ Zero-shot and few-shot techniques+ 1 more lessons
05
FastAPI Backend with Bedrock
→ Architecture of an AI backend→ Create a FastAPI API + Bedrock+ 1 more lessons
06
Streamlit Frontend for AI
→ Chat interface with Streamlit→ Conversation history and memory+ 1 more lessons
07
RAG Retrieval Augmented Generation
→ What is RAG?→ Embeddings and vector database+ 1 more lessons
08
Knowledge Bases and Bedrock Agents
→ Bedrock Knowledge Bases→ Bedrock Agents and actions+ 2 more lessons
🏁
Final project (+ 3 chapters along the way)
→ You leave with a concrete and demonstrable project

Install Boto3 and configure credentials

NOTELesson objective: By the end of this section, you will be able to install the Python SDK Boto3, configure your AWS credentials, and verify that your connection to AWS Bedrock works correctly from a Python script.
TIPPrerequisites: You must have an AWS account with Amazon Bedrock access enabled (see Chapter 01). No prior knowledge of Boto3 is required.

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.

NOTEAnalogy: Think of AWS as a huge restaurant with hundreds of dishes. Boto3 is the waiter who takes your orders (API calls) and brings back the results. Without Boto3, you would have to shout your orders through the kitchen window (raw HTTP requests) — possible, but far less convenient.

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:

bash
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.

bash
# Verification after installation
python --version
pip --version

macOS

bash
# Via Homebrew (recommended)
brew install python@3.11

# Verification
python3 --version
pip3 --version

Linux (Ubuntu / Debian)

bash
sudo apt update
sudo apt install python3 python3-pip python3-venv -y

# Verification
python3 --version
pip3 --version
WARNINGAttention: On macOS and Linux, use 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.

NOTEAnalogy: A virtual environment is like a dedicated toolbox for a construction site. Each site (project) has its own box with its own tools (libraries). No mixing between sites.

Create and activate the venv

First call to Bedrock via the console

NOTELesson objective: Navigate the AWS Bedrock console, enable model access, send your first prompt in the Playground, and understand generation parameters (temperature, max tokens, top-p).

Learning objectives

1 – Access Amazon Bedrock

Step 1: Sign in to the AWS console

Open your browser and go to:

bash
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

WARNINGRegion notice: Bedrock is not available in every region. Make sure you are in a supported region. We recommend US East (N. Virginia) – us-east-1 to access all models.

Check the region in the top-right corner of the console:

output
+----------------------------------------------------------+
|  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:

output
+----------------------------------------------------------+
|  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):

output
+----------------------------+------------------------------+
|  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:

output
+----------------------------------------------------------+
|  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.

TIPTip: You can safely enable all models at once. You pay nothing until you actually make calls. Activation is free.

Create a FastAPI + Bedrock API

Full Stack AI with AWS Bedrock • FastAPI Backend with Bedrock

NOTEObjective: Build, step by step, a complete FastAPI that receives a user message and returns the response generated by AWS Bedrock (Claude). By the end of this lesson you will have a working /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:

bash
# 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:

bash
pip list | findstr -i "fastapi uvicorn boto3"

You should see the three libraries with their version numbers.

TIPAnalogy: Installing dependencies is like gathering your ingredients before cooking. FastAPI is the pan, Uvicorn is the heat, and Boto3 is the main ingredient that connects to AWS.

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.

output
# 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: str
NOTEWhy Pydantic? Without Pydantic you must manually validate every field (is it a string? is it empty? is the number in range?). Pydantic does all of this automatically and produces clear error messages for the frontend.

If the frontend sends a temperature value of 5.0 (outside the 0-1 range), Pydantic returns:

output
{
  "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.

output
# 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.

output
# 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"
            },
        ]
    }
go-further

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 Code

FAQ

How long does it take to learn Full Stack AI AWS Bedrock?
With a structured progression (12 chapters, 41 short practical lessons), you reach an operational level in a few weeks at 30–60 minutes per day. The key is to practice each concept immediately.
Are there any prerequisites?
Basic computer literacy is enough. If you can use a terminal and read simple code, you are ready.
Where to start concretely?
Reproduce the commands in this article, then follow the complete Full Stack AI AWS Bedrock course: it walks through the 41 lessons in order, with exercises and a final project.

📬 Want to receive this kind of guide every week? Subscribe for free — real code, zero fluff.