Use Django MongoDB Backend with Azure DocumentDB: Build an inventory API

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

You learn how to:

  • Map a Django model to a collection with ObjectIds.
  • Create indexes with Django migrations.
  • 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 for this example. 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 permissions to create collections and indexes and perform CRUD. 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 running migrations or starting the API.
  • A private endpoint or firewall access for your development IP.

Tested driver version

This tutorial was tested with Django MongoDB Backend 6.1.0 and PyMongo 4.19.0 using Microsoft Entra ID authentication. The backend depends on PyMongo, which the install command pins to the tested version.

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 API is only for local development. It doesn't authenticate HTTP callers and exempts these stateless JSON endpoints from CSRF checks. Don't deploy it unchanged or add cookie authentication without restoring CSRF protection. Add authentication, authorization, HTTPS, and rate limits. For production database access, use managed identity, private endpoints, and disabled public network access. DefaultAzureCredential can use your Azure CLI session locally and managed identity in Azure.

Understand the scenario

Use database adventureworks_django and collection products. Products have a unique SKU, name, category, price in integer cents, and nonnegative quantity. This example uses a single currency and limits numeric inputs to signed 32-bit integers.

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.

The stock filter prevents negative inventory, not duplicate reservations. A timeout can leave the outcome unknown. Driver-managed retries aren't the same as starting a new application operation; implement persisted reservation identifiers and concurrency-safe deduplication before application-level retries.

Create the project

  1. Create and activate a virtual environment.

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

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

  2. Install dependencies and create the project and app.

    python -m pip install "Django==6.1.3" "django-mongodb-backend==6.1.0" "pymongo==4.19.0" "python-dotenv>=1,<2" "azure-identity>=1.27,<2"
    django-admin startproject inventory .
    python manage.py startapp catalog
    
  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_django
    

    Use the hostname from Verify the cluster from a terminal. Don't include credentials or SCRAM options in the Entra URI. To use native authentication instead, set MONGODB_AUTH=password and use the password URI from the terminal setup. Don't commit secrets. retryWrites=false is a sample setting, not a service requirement.

  4. Replace inventory/settings.py with this minimal configuration. It intentionally excludes Django admin, sessions, and authentication applications.

    import os
    import time
    from pathlib import Path
    from azure.identity import DefaultAzureCredential
    from dotenv import load_dotenv
    from pymongo.auth_oidc import OIDCCallback, OIDCCallbackResult
    
    
    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())
    
    
    BASE_DIR = Path(__file__).resolve().parent.parent
    load_dotenv(BASE_DIR / ".env")
    auth = os.environ["MONGODB_AUTH"]
    options = {"serverSelectionTimeoutMS": 30000}
    if auth == "entra":
        options.update(authSource="$external", authMechanism="MONGODB-OIDC",
                       authMechanismProperties={"OIDC_CALLBACK": EntraCallback()})
    elif auth != "password":
        raise ValueError("Set MONGODB_AUTH to entra or password.")
    SECRET_KEY = "local-development-only-not-for-deployment"
    DEBUG = False
    ALLOWED_HOSTS = ["127.0.0.1", "localhost"]
    INSTALLED_APPS = ["catalog"]
    MIDDLEWARE = []
    ROOT_URLCONF = "inventory.urls"
    DATABASES = {"default": {
        "ENGINE": "django_mongodb_backend",
        "HOST": os.environ["MONGODB_URI"],
        "NAME": os.environ["MONGODB_DATABASE"],
        "OPTIONS": options,
    }}
    DEFAULT_AUTO_FIELD = "django_mongodb_backend.fields.ObjectIdAutoField"
    DATA_UPLOAD_MAX_MEMORY_SIZE = 16384
    USE_TZ = True
    
  5. Replace inventory/urls.py with an empty URL configuration before running migrations. The generated configuration references Django admin, which isn't installed in this example. You add the product routes after implementing the views.

    urlpatterns = []
    

Define the product model

Replace catalog/models.py:

from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django_mongodb_backend.fields import ObjectIdAutoField


class Product(models.Model):
    id = ObjectIdAutoField(primary_key=True)
    sku = models.CharField(max_length=64, unique=True)
    name = models.CharField(max_length=200)
    category = models.CharField(max_length=100)
    priceCents = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(2147483647)])
    quantity = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(2147483647)])

    class Meta:
        db_table = "products"
        indexes = [models.Index(fields=["category", "name", "id"], name="category_name_id")]

Create collections and indexes before accepting requests:

python manage.py makemigrations catalog
python manage.py migrate

The backend creates the unique SKU and compound list index. Only _id is indexed by the service by default. Keep generated migration files with the application and review migrations before deployment. Model validators aren't database constraints and don't automatically run on save() or query updates.

Implement the API

Replace catalog/views.py:

import json
from functools import wraps

from bson import ObjectId
from bson.errors import InvalidId
from django.core.exceptions import RequestDataTooBig, ValidationError
from django.db import DatabaseError, IntegrityError, connection
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from pymongo import ReturnDocument
from pymongo.errors import BulkWriteError, DuplicateKeyError, PyMongoError

from .models import Product


def output(product):
    fields = ("sku", "name", "category", "priceCents", "quantity")
    if isinstance(product, dict):
        return {"_id": str(product["_id"]), **{field: product[field] for field in fields}}
    return {"_id": str(product.pk), **{field: getattr(product, field) for field in fields}}


def endpoint(view):
    @csrf_exempt
    @wraps(view)
    def wrapped(request, *args, **kwargs):
        try:
            return view(request, *args, **kwargs)
        except (IntegrityError, DuplicateKeyError):
            return JsonResponse({"error": "SKU already exists."}, status=409)
        except RequestDataTooBig:
            return JsonResponse({"error": "Request body is too large."}, status=413)
        except (ValueError, InvalidId, ValidationError):
            return JsonResponse({"error": "Invalid request fields or JSON."}, status=400)
        except (DatabaseError, PyMongoError) as error:
            if isinstance(error, BulkWriteError):
                failures = error.details.get("writeErrors", [])
                if failures and all(item.get("code") == 11000 for item in failures) and not error.details.get("writeConcernErrors"):
                    return JsonResponse({"error": "SKU already exists."}, status=409)
            print("Database request failed:", type(error).__name__)
            return JsonResponse({"error": "The request could not be completed."}, status=500)
    return wrapped


def body(request, allowed, required=()):
    if request.content_type != "application/json":
        raise ValueError("Provide JSON.")
    data = json.loads(request.body)
    if not isinstance(data, dict) or not data or set(data) - set(allowed) or set(required) - set(data):
        raise ValueError("Invalid fields.")
    for field, value in data.items():
        if field in ("quantity", "priceCents"):
            if type(value) is not int or not 0 <= value <= 2147483647:
                raise ValueError("Invalid integer.")
        else:
            limit = {"sku": 64, "name": 200, "category": 100}[field]
            if not isinstance(value, str) or not 1 <= len(value.strip()) <= limit:
                raise ValueError("Invalid text.")
            data[field] = value.strip()
    return data


@endpoint
def products(request):
    if request.method == "POST":
        fields = ("sku", "name", "category", "priceCents", "quantity")
        product = Product(**body(request, fields, fields))
        product.full_clean(validate_unique=False)
        product.save(force_insert=True)
        return JsonResponse(output(product), status=201)
    if request.method == "GET":
        category = request.GET.get("category", "").strip()
        page_text = request.GET.get("page", "1")
        if not 1 <= len(category) <= 100 or not page_text.isascii() or not page_text.isdigit():
            raise ValueError("Invalid category or page.")
        page = int(page_text)
        if not 1 <= page <= 1000:
            raise ValueError("Invalid page.")
        rows = Product.objects.filter(category=category).order_by("name", "id")[(page - 1) * 20:page * 20]
        return JsonResponse({"page": page, "products": [output(row) for row in rows]})
    return HttpResponse(status=405)


@endpoint
def detail(request, product_id):
    identity = ObjectId(product_id)
    if request.method == "PATCH":
        changes = body(request, ("name", "category", "priceCents"))
        updated = connection.database["products"].find_one_and_update(
            {"_id": identity}, {"$set": changes}, return_document=ReturnDocument.AFTER
        )
        if updated is None:
            return JsonResponse({"error": "Product not found."}, status=404)
        return JsonResponse(output(updated))
    if request.method == "DELETE":
        deleted, _ = Product.objects.filter(pk=identity).delete()
        return HttpResponse(status=204) if deleted else JsonResponse({"error": "Product not found."}, status=404)
    return HttpResponse(status=405)


@endpoint
def reserve(request, product_id):
    identity = ObjectId(product_id)
    if request.method != "POST":
        return HttpResponse(status=405)
    amount = body(request, ("quantity",), ("quantity",))["quantity"]
    if amount == 0:
        raise ValueError("Quantity must be positive.")
    updated = connection.database["products"].find_one_and_update(
        {"_id": identity, "quantity": {"$gte": amount}},
        {"$inc": {"quantity": -amount}}, return_document=ReturnDocument.AFTER,
    )
    if updated is None:
        return JsonResponse({"error": "Product not found or insufficient inventory."}, status=409)
    return JsonResponse(output(updated))

The reservation and patch use PyMongo through the backend connection so each update returns the document from that same atomic operation. These calls bypass Django model validation, signals, and ORM transaction handling. The code explicitly validates inputs. Don't pass arbitrary request bodies to PyMongo. This tutorial doesn't mix these calls with an ORM transaction.

Replace inventory/urls.py:

from django.urls import path
from catalog import views

urlpatterns = [
    path("products", views.products),
    path("products/<str:product_id>", views.detail),
    path("products/<str:product_id>/reserve", views.reserve),
]

The list index supports category filtering and stable ordering. Pagination uses offsets for simplicity; prefer cursors for large catalogs. The backend reuses connection pools. Don't create a new MongoClient in each view.

Run the application

Reuse the DATABASES settings and let Django manage its connections. The inventory views and HTTP test data are examples, not application infrastructure.

Start the development server, bound to loopback:

python manage.py runserver 127.0.0.1:3000 --noreload

The server reports that it is listening on http://127.0.0.1:3000. This configuration isn't production-ready. Existing environment variables take precedence over .env.

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
Django rejects an auto field or application configuration. Match backend and Django 6.1 versions and use ObjectIdAutoField. Don't reintroduce generated relational admin/auth settings unchanged.
E11000 during python manage.py migrate Use a dedicated tutorial database without duplicate SKUs.
ServerSelectionTimeoutError Run the SRV lookup in the terminal setup from the machine that runs the app.
The API returns 400. Check JSON content type, field names, integer bounds, and ObjectId syntax.
The API returns 409. Check duplicate SKUs or insufficient inventory.

Inspect diagnostics locally and remove credentials before sharing them. Database details aren't returned to API callers.

Clean up resources

The test deletes its product but leaves the database and migration history.

  1. Stop the server with Ctrl+C.
  2. Delete only the adventureworks_django 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.