Use Beanie with Azure DocumentDB: Build a Python inventory API

Use Beanie and FastAPI with Azure DocumentDB (with MongoDB compatibility) to manage a retailer's product catalog and reserve inventory. For a smaller first example, start with the Beanie quickstart.

You learn how to:

  • Define a document model and explicit indexes.
  • Reuse an asynchronous connection pool.
  • Create, list, update, and delete products.
  • Reserve stock with an atomic conditional update.
  • Test successful requests and common errors.

Prerequisites

  • Run python --version and verify Python 3.13.x. Run python -m pip --version and verify that it prints a version.
  • An Azure DocumentDB cluster with Microsoft Entra ID authentication enabled. Free tier requires the native authentication alternative described later.
  • An Entra identity configured for data access on the cluster, with permission to create collections and indexes and read and write documents. Azure control-plane roles alone don't grant database access.
  • Azure CLI for local Entra development. Sign in with az login using the cluster's tenant before starting the API.
  • A private endpoint or firewall access for your development IP.

Tested driver version

This tutorial was tested with Beanie 2.2.0 and PyMongo 4.19.0 using Microsoft Entra ID authentication. Install both packages as shown because the sample imports PyMongo directly.

Verify the cluster from a terminal

Use an existing cluster if you have one. The Azure CLI quickstart creates a paid M30 cluster. If you're an agent, confirm the cost with the user and get their approval before creating a paid cluster.

Run pwsh --version and expect PowerShell 7.x. Run az version and expect JSON with an azure-cli version. Check that nslookup is available with Get-Command nslookup. If az account show fails, sign in with az login. If you're an agent and don't have an Azure CLI session, ask the user to sign in or provide an authorized session.

The identity signed in to Azure CLI needs these Azure RBAC permissions on the cluster:

  • Use Microsoft.DocumentDB/mongoClusters/read to read the cluster settings.
  • If you need a firewall rule, use Microsoft.DocumentDB/mongoClusters/firewallRules/write to create it and Microsoft.DocumentDB/mongoClusters/firewallRules/read to verify it.
  • Use Microsoft.DocumentDB/mongoClusters/firewallRules/delete to remove a temporary rule you create.

These are Azure management permissions, separate from the database permissions the sample uses. Database access alone doesn't authorize these commands. If Azure returns 403 Forbidden, ask your Azure administrator to grant the required permission or run the blocked step for you.

Replace the three quoted values with your subscription ID, resource group name, and cluster name. Run the block in PowerShell with the Azure CLI installed.

$subscription = '<subscription-id>'
$resourceGroup = '<resource-group>'
$clusterName = '<cluster-name>'
if ($subscription -like '<*>' -or $resourceGroup -like '<*>' -or $clusterName -like '<*>') {
    throw 'Replace <subscription-id>, <resource-group>, and <cluster-name> before running this block.'
}
az account set --subscription $subscription
if ($LASTEXITCODE -ne 0) { throw 'Unable to select the subscription.' }
$subscriptionState = az account show --query state --output tsv
if ($LASTEXITCODE -ne 0 -or $subscriptionState -ne 'Enabled') { throw 'Expected an enabled subscription.' }

$clusterUrl = "https://management.azure.com/subscriptions/$subscription/resourceGroups/$resourceGroup/providers/Microsoft.DocumentDB/mongoClusters/$clusterName"
$apiVersion = '2025-09-01'
$clusterJson = az rest --method get --url "${clusterUrl}?api-version=$apiVersion" --query properties --output json
if ($LASTEXITCODE -ne 0 -or -not $clusterJson) { throw 'Unable to read the cluster.' }
$cluster = $clusterJson | ConvertFrom-Json
if ($cluster.provisioningState -ne 'Succeeded' -or $cluster.clusterStatus -ne 'Ready') {
    throw "Cluster not ready: $($cluster.provisioningState), $($cluster.clusterStatus)."
}
if (-not $cluster.connectionString) { throw 'Unable to retrieve the connection string template.' }
$clusterHost = ([uri] ($cluster.connectionString -replace '^mongodb\+srv://(?:[^/]*@)?', 'https://')).Host
"Cluster host: $clusterHost"
"Server version: $($cluster.serverVersion)"
"Public network access: $($cluster.publicNetworkAccess)"
nslookup -type=SRV "_mongodb._tcp.$clusterHost"
if ($LASTEXITCODE -ne 0) { throw 'SRV lookup failed.' }

Expect the cluster hostname, a server version such as 8.0, and one or more SRV targets. If nslookup doesn't show any SRV targets, stop and check DNS from the machine that runs the sample. Save the hostname for later steps. It typically has the form <cluster-name>.mongocluster.cosmos.azure.com or <cluster-name>.global.mongocluster.cosmos.azure.com. Use the returned hostname instead of constructing it from the cluster name.

Public access only. If the cluster reports Enabled for public network access and no existing rule allows the machine that runs the sample, allow only that machine's public IPv4 address.

If the sample runs behind a proxy or in a cloud sandbox, the IP address that curl returns might change or differ from the address the database sees. Use a reachable private endpoint instead, or stop and ask the user for a stable network path. Don't keep adding firewall rules.

Run curl --version and expect a version line starting with curl. Run the cluster verification and firewall blocks in one PowerShell session. If your tool starts a new session for each command, run both blocks as one script.

$clientIp = curl --fail --silent --show-error --max-time 10 -4 https://ifconfig.me/ip
if ($LASTEXITCODE -ne 0) { throw 'Unable to determine the public IPv4 address.' }
$parsedIp = $null
if (-not [ipaddress]::TryParse($clientIp, [ref]$parsedIp) -or
    $parsedIp.AddressFamily -ne 'InterNetwork' -or $parsedIp.ToString() -ne $clientIp) {
    throw 'Expected a public IPv4 address in dotted-decimal format.'
}

$ruleName = "allow-framework-sample-$($clientIp.Replace('.', '-'))"
$ruleId = "$(([uri]$clusterUrl).AbsolutePath)/firewallRules/$ruleName"
$ruleUrl = "$clusterUrl/firewallRules/${ruleName}?api-version=$apiVersion"
$body = @{ properties = @{ startIpAddress = $clientIp; endIpAddress = $clientIp } } | ConvertTo-Json
$bodyFile = New-TemporaryFile
try {
    Set-Content -LiteralPath $bodyFile.FullName -Value $body -Encoding utf8 -ErrorAction Stop
    az rest --method put --url $ruleUrl --headers 'Content-Type=application/json' --body "@$($bodyFile.FullName)" --output none
    if ($LASTEXITCODE -ne 0) { throw 'Unable to create the firewall rule.' }
} finally {
    Remove-Item -LiteralPath $bodyFile.FullName
}
"Firewall rule ID: $ruleId"
az resource wait --created --ids $ruleId --api-version $apiVersion --interval 5 --timeout 120
if ($LASTEXITCODE -ne 0) { throw 'The firewall rule did not finish provisioning. Check the rule before retrying.' }
az rest --method get --url $ruleUrl --query "properties.{start:startIpAddress,end:endIpAddress}" --output table
if ($LASTEXITCODE -ne 0) { throw 'Unable to verify the firewall rule.' }

Expect the same IPv4 address in the Start and End columns. If you created the rule for this sample, save the value after Firewall rule ID: for cleanup. If you rerun the block from the same public IPv4 address, it updates the same rule instead of creating another one.

Firewall changes can take up to 15 minutes to propagate. If the initial connection times out after you create the rule, retry the connection every 2 minutes, for up to 15 minutes after you create the rule. Stop if the connection succeeds or returns a different error. Don't recreate the rule while you wait.

For private access, skip the firewall block and run the sample from a machine that can resolve and reach the private endpoint. Don't enable public access just to run the sample.

Follow only the authentication path that your example uses.

Microsoft Entra ID. Follow the CLI steps to enable Microsoft Entra ID authentication and assign a data-plane identity. Azure resource permissions alone don't grant database access. Put the discovered hostname in the example's credential-free URI. Skip the password steps and don't reuse a password-based URI.

Password authentication. If your environment already provides the connection variable the sample needs (MONGODB_URI, or DATABASE_URL for Prisma), skip URI construction.

az rest returns a connection string template, not the password. To find the native administrator username, add $cluster.administrator.userName at the end of the cluster verification block.

  • Agents (noninteractive). Ask the user to set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD as environment variables through your tool's secret settings. Don't ask for credentials in chat, put them in command text, or reset the password.

  • Interactive PowerShell. In PowerShell 7.1 or later, run the following commands in the same session you use to build the URI. Enter your existing credentials at the prompts. Don't put the password in command text.

    $env:DOCUMENTDB_USERNAME = Read-Host 'Native username'
    $env:DOCUMENTDB_PASSWORD = Read-Host 'Native password' -MaskInput
    

Replace <cluster-host> with the hostname from the verification output. Run this block to set MONGODB_URI without printing the credentials or the URI. You don't need variables from the cluster verification session.

$clusterHost = '<cluster-host>'
if ($clusterHost -like '<*>') { throw 'Replace <cluster-host> with the hostname from the verification output.' }
if ([string]::IsNullOrWhiteSpace($env:DOCUMENTDB_USERNAME) -or
    [string]::IsNullOrEmpty($env:DOCUMENTDB_PASSWORD)) {
    throw 'Set DOCUMENTDB_USERNAME and DOCUMENTDB_PASSWORD before building the URI. If you are an agent, ask the user to supply them through your tool''s secret settings.'
}
try {
    $encodedUser = [uri]::EscapeDataString($env:DOCUMENTDB_USERNAME)
    $encodedPassword = [uri]::EscapeDataString($env:DOCUMENTDB_PASSWORD)
    $env:MONGODB_URI = "mongodb+srv://${encodedUser}:${encodedPassword}@${clusterHost}/?tls=true&authSource=admin&authMechanism=SCRAM-SHA-256&retryWrites=false&serverSelectionTimeoutMS=30000"
} finally {
    Remove-Variable encodedUser, encodedPassword -ErrorAction SilentlyContinue
    Remove-Item Env:DOCUMENTDB_USERNAME, Env:DOCUMENTDB_PASSWORD -ErrorAction SilentlyContinue
}

Prisma only. If your environment already provides DATABASE_URL, skip this step. Otherwise, replace <database-name> with the database name in your Prisma example. Run this block in the same PowerShell session as URI construction to add the database name to the URI path and set DATABASE_URL. If your tool starts a new session for each command, run both blocks as one script.

$databaseName = '<database-name>'
if ($databaseName -like '<*>') { throw 'Replace <database-name> with the database name in your Prisma example.' }
$env:DATABASE_URL = $env:MONGODB_URI.Replace('/?', "/${databaseName}?")
Remove-Item Env:MONGODB_URI

Save the URI for a new shell

If your sample loads .env, you can save the URI there to run the sample in a new shell. If you haven't created the project yet, continue to the project setup in your article before running these steps. Use a private local workspace because .env stores the URI in plaintext.

  1. In the sample project directory, run git --version and expect a Git version.

  2. If the project isn't in a Git repository, run git init. Add .env to .gitignore and keep any other settings the sample requires in .env.

  3. Run the following block in the PowerShell session where you set MONGODB_URI or DATABASE_URL. If your tool starts a new session for each command, run URI construction, the Prisma step if applicable, and this block as one script.

    $uriKey = 'MONGODB_URI' # Use 'DATABASE_URL' for Prisma.
    $uriValue = [Environment]::GetEnvironmentVariable($uriKey)
    if (-not $uriValue) { throw "Set $uriKey before writing .env." }
    git check-ignore -q -- .env
    if ($LASTEXITCODE -ne 0) { throw 'Make sure .env is ignored and not tracked by Git.' }
    if ((Test-Path -LiteralPath .env) -and (Select-String -Quiet -LiteralPath .env -Pattern "^\s*(?:export\s+)?${uriKey}\s*=")) {
        throw "Remove the existing $uriKey line from .env before running this block."
    }
    Add-Content -LiteralPath .env -Value "`n$uriKey=$uriValue" -Encoding utf8 -ErrorAction Stop
    Remove-Variable uriValue
    Remove-Item "Env:$uriKey"
    "Saved $uriKey to the ignored .env file."
    

    Expect Saved MONGODB_URI to the ignored .env file. or Saved DATABASE_URL to the ignored .env file. You can now continue with the article in a new shell. Run the sample from the project directory.

If the sample doesn't load .env or you can't store secrets in the workspace, configure your tool to pass the URI to each command that needs it. Alternatively, run URI construction and the sample as one script.

When you're done, remove the connection entry from .env if you added it. Clear any URI variables with Remove-Item Env:MONGODB_URI, Env:DATABASE_URL -ErrorAction SilentlyContinue. Don't print or commit connection strings.

Important

This local API doesn't authenticate HTTP callers. Before exposing it, add API authentication, authorization, HTTPS, and rate limits. For production database access, use managed identity, private endpoints, and disabled public network access. The Entra callback uses DefaultAzureCredential, which can use your Azure CLI session locally and managed identity in Azure.

Already using Beanie?

If your app uses Beanie 1 with Motor, stop and update the app to Beanie 2 and PyMongo's AsyncMongoClient before using this setup. For an existing Beanie 2 app, set MONGODB_URI and pass client[MONGODB_DATABASE] to init_beanie(). This change doesn't copy documents, indexes, or users. Use Migration options to plan data movement and provision database users separately.

Review feature compatibility and query compatibility. Beanie links, aggregation pipelines, transactions, and plugins still require workload-specific tests; this single-document sample doesn't certify them. Query updates bypass model validation, so the API validates each input before writing.

Understand the scenario

Use database adventureworks_beanie and collection products. Products have a unique SKU, name, category, price in integer cents, and nonnegative quantity. This example limits numeric inputs to signed 32-bit integers for consistent behavior across the framework samples. Prices use a single currency.

Method Endpoint Purpose
POST /products Create a product.
GET /products?category=gear&page=1 List 20 products in stable name and ID order.
PATCH /products/:id Update name, category, or price.
POST /products/:id/reserve Decrease quantity if sufficient stock remains.
DELETE /products/:id Delete a product.

Reservations don't create orders or coordinate multiple products. The stock filter prevents negative inventory, not duplicate reservations. A timeout can leave the outcome unknown. Driver-managed retries differ from starting a new application operation; add persisted reservation identifiers and concurrency-safe deduplication before application-level retries.

Create the project

  1. Create a project and virtual environment, then activate it.

    mkdir documentdb-beanie-inventory
    cd documentdb-beanie-inventory
    python -m venv .venv
    

    On Windows, run .venv\Scripts\Activate.ps1. On macOS or Linux, run source .venv/bin/activate.

  2. Install dependencies.

    python -m pip install "beanie==2.2.0" "pymongo==4.19.0" "fastapi>=0.115,<1" "uvicorn>=0.30,<1" "python-dotenv>=1,<2" "azure-identity>=1.27,<2"
    
  3. Add .venv/, .env, and __pycache__/ to .gitignore. Create .env:

    MONGODB_AUTH=entra
    MONGODB_URI=mongodb+srv://<cluster-host>/?tls=true&retryWrites=false
    MONGODB_DATABASE=adventureworks_beanie
    

    Use the hostname from Verify the cluster from a terminal. Don't put a username, password, or SCRAM mechanism in the Entra URI. Existing environment variables take precedence over .env.

    For native authentication, set MONGODB_AUTH=password and use the password URI from the terminal setup. Don't commit secrets.

    retryWrites=false is a sample configuration, not a service requirement. Verify retry support and requirements for your deployment before production use.

Define the model and API

Create app.py:

import os
import time
from contextlib import asynccontextmanager
from typing import Annotated

from azure.identity import DefaultAzureCredential
from beanie import Document, PydanticObjectId, init_beanie
from beanie.odm.queries.update import UpdateResponse
from bson.errors import InvalidId
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Query, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
from pymongo import AsyncMongoClient, IndexModel
from pymongo.auth_oidc import OIDCCallback, OIDCCallbackResult
from pymongo.errors import DuplicateKeyError, PyMongoError

ShortText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=100)]
Name = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=200)]
Sku = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=64)]
Count = Annotated[int, Field(strict=True, ge=0, le=2147483647)]


class Product(Document):
    sku: Sku
    name: Name
    category: ShortText
    priceCents: Count
    quantity: Count

    class Settings:
        name = "products"
        indexes = [IndexModel([("sku", 1)], unique=True),
                   IndexModel([("category", 1), ("name", 1), ("_id", 1)])]


class CreateProduct(BaseModel):
    model_config = ConfigDict(extra="forbid")
    sku: Sku
    name: Name
    category: ShortText
    priceCents: Count
    quantity: Count


class PatchProduct(BaseModel):
    model_config = ConfigDict(extra="forbid")
    name: Name | None = None
    category: ShortText | None = None
    priceCents: Count | None = None


class Reservation(BaseModel):
    model_config = ConfigDict(extra="forbid")
    quantity: Annotated[int, Field(strict=True, gt=0, le=2147483647)]


class EntraCallback(OIDCCallback):
    def __init__(self):
        self.credential = DefaultAzureCredential()

    def fetch(self, context):
        token = self.credential.get_token("https://ossrdbms-aad.database.windows.net/.default")
        return OIDCCallbackResult(access_token=token.token,
                                  expires_in_seconds=token.expires_on - time.time())


@asynccontextmanager
async def lifespan(app):
    load_dotenv()
    auth = os.environ["MONGODB_AUTH"]
    if auth not in {"entra", "password"}:
        raise ValueError("Set MONGODB_AUTH to entra or password.")
    callback = EntraCallback() if auth == "entra" else None
    options = {"serverSelectionTimeoutMS": 30000}
    if callback:
        options.update(authSource="$external", authMechanism="MONGODB-OIDC",
                       authMechanismProperties={"OIDC_CALLBACK": callback})
    try:
        async with AsyncMongoClient(os.environ["MONGODB_URI"], **options) as client:
            await init_beanie(database=client[os.environ["MONGODB_DATABASE"]], document_models=[Product])
            yield
    finally:
        if callback:
            callback.credential.close()


app = FastAPI(lifespan=lifespan)


def identifier(value):
    try:
        return PydanticObjectId(value)
    except (InvalidId, ValueError, TypeError):
        raise HTTPException(400, "Invalid product ID.") from None


def output(product):
    return {"_id": str(product.id), "sku": product.sku, "name": product.name,
            "category": product.category, "priceCents": product.priceCents,
            "quantity": product.quantity}


@app.exception_handler(RequestValidationError)
async def invalid_request(request: Request, error: RequestValidationError):
    return JSONResponse(status_code=400, content={"error": "Invalid request fields."})


@app.exception_handler(DuplicateKeyError)
async def duplicate(request: Request, error: DuplicateKeyError):
    return JSONResponse(status_code=409, content={"error": "SKU already exists."})


@app.exception_handler(PyMongoError)
async def database_error(request: Request, error: PyMongoError):
    print("Database request failed:", type(error).__name__, getattr(error, "code", None))
    return JSONResponse(status_code=500, content={"error": "The request could not be completed."})


@app.post("/products", status_code=201)
async def create(body: CreateProduct):
    return output(await Product(**body.model_dump()).insert())


@app.get("/products")
async def listing(category: str = Query(min_length=1, max_length=100),
                  page: int = Query(default=1, ge=1, le=1000)):
    if not category.strip():
        raise HTTPException(400, "Provide a category.")
    products = await Product.find(Product.category == category.strip()).sort(
        +Product.name, +Product.id
    ).skip((page - 1) * 20).limit(20).to_list()
    return {"page": page, "products": [output(product) for product in products]}


@app.patch("/products/{product_id}")
async def patch(product_id: str, body: PatchProduct):
    updates = body.model_dump(exclude_unset=True)
    if not updates or any(value is None for value in updates.values()):
        raise HTTPException(400, "Provide name, category, or priceCents.")
    product = await Product.find_one(Product.id == identifier(product_id)).update(
        {"$set": updates}, response_type=UpdateResponse.NEW_DOCUMENT
    )
    if product is None:
        raise HTTPException(404, "Product not found.")
    return output(product)


@app.post("/products/{product_id}/reserve")
async def reserve(product_id: str, body: Reservation):
    product = await Product.find_one(
        Product.id == identifier(product_id), Product.quantity >= body.quantity
    ).update({"$inc": {"quantity": -body.quantity}}, response_type=UpdateResponse.NEW_DOCUMENT)
    if product is None:
        raise HTTPException(409, "Product not found or insufficient inventory.")
    return output(product)


@app.delete("/products/{product_id}", status_code=204)
async def delete(product_id: str):
    result = await Product.find_one(Product.id == identifier(product_id)).delete()
    if result.deleted_count == 0:
        raise HTTPException(404, "Product not found.")
    return Response(status_code=204)

Beanie creates the declared indexes before accepting requests and reuses one client for the application lifetime. Only _id is indexed by the service by default. Don't enable index dropping to resolve an index conflict. In production, move index management to a controlled deployment step.

The reservation predicate and $inc execute as one update. Don't replace this update with a read followed by save(), which can lose concurrent updates. The API validates update values explicitly because Beanie query updates don't run Pydantic field validation. Pagination uses skip for simplicity; use cursor-based pagination for large catalogs.

Run the application

Reuse the FastAPI lifespan setup to share one AsyncMongoClient per process. The inventory routes and HTTP test data are examples, not application infrastructure.

Start the local API:

python -m uvicorn app:app --host 127.0.0.1 --port 3000

The terminal reports that application startup is complete and the server is listening on http://127.0.0.1:3000. If initialization fails, check authentication and index permissions before testing HTTP requests.

Test the API

Keep the API running and open a second terminal with curl installed. These requests don't require another programming language. On Windows PowerShell, use curl.exe instead of curl to avoid its Invoke-WebRequest alias. Each command prints response headers, including the HTTP status, followed by the JSON body.

  1. Create product.json in the test terminal's working directory. Use a unique SKU for each test run, and keep it unchanged for the duplicate request.

    {
      "sku": "SURF-CURL-001",
      "name": "Yamba Surfboard",
      "category": "gear-surf-surfboards",
      "priceCents": 85000,
      "quantity": 12
    }
    
  2. Create the product. Expect 201, quantity 12, and an _id string. Record this ID and replace <product-id> in the following commands with it.

    curl --include --request POST "http://127.0.0.1:3000/products" --header "Content-Type: application/json" --data-binary "@product.json"
    
  3. Run the same command again. Expect 409 because the SKU already exists.

  4. List products in the category. Expect 200 and a products array. The list returns 20 products per page; your product might be on a later page if the category already contains data.

    curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"
    
  5. Create price.json:

    { "priceCents": 82000 }
    

    Update the price. Expect 200 and priceCents equal to 82000.

    curl --include --request PATCH "http://127.0.0.1:3000/products/<product-id>" --header "Content-Type: application/json" --data-binary "@price.json"
    
  6. Create reservation.json:

    { "quantity": 2 }
    

    Reserve two units. Expect 200 and quantity 10.

    curl --include --request POST "http://127.0.0.1:3000/products/<product-id>/reserve" --header "Content-Type: application/json" --data-binary "@reservation.json"
    
  7. Change the quantity in reservation.json to 11 and repeat the reservation command. Expect 409 because only 10 units remain. Then change it to -1 and repeat. Expect 400.

  8. Change priceCents in price.json to -1 and repeat the price update command. Expect 400.

  9. Try an invalid ID. Expect 400.

    curl --include --request DELETE "http://127.0.0.1:3000/products/not-an-objectid"
    
  10. Delete only the product created in this test, even if an earlier check failed. Expect 204 with no body. Repeat the command and expect 404.

    curl --include --request DELETE "http://127.0.0.1:3000/products/<product-id>"
    
  11. List the category again. Expect 200 and verify that the deleted _id is no longer present.

    curl --include "http://127.0.0.1:3000/products?category=gear-surf-surfboards&page=1"
    

Remove the three local JSON files when you finish. If you use another API port, replace 3000 in the commands.

Troubleshoot common issues

Symptom Action
OperationFailure with code 18 Verify your authentication mode and identity using the terminal setup.
ServerSelectionTimeoutError Run the SRV lookup in the terminal setup from the machine that runs the app.
E11000 Use a dedicated tutorial database without duplicate SKUs.
The API returns 400. Check ObjectId syntax, required fields, integer bounds, and JSON syntax.
The API returns 409. Use a unique SKU or verify that enough stock remains.
Port 3000 is occupied. Change --port 3000 in the Uvicorn command to an available port and replace 3000 in the curl test commands with that port.

Don't share raw startup tracebacks without removing credentials. Database errors aren't returned to HTTP callers. Add request size limits at the hosting layer before deployment.

Clean up resources

The test deletes its product but leaves the collection and indexes.

  1. Stop the server with Ctrl+C.
  2. Delete only the adventureworks_beanie database if you no longer need it.
  3. Delete the cluster only if you created it exclusively for this tutorial.
  4. Remove temporary firewall rules.