Azure Cosmos DB Py
MicrosoftOfficialCreated by Microsoft
- Skill
- Tool integration
- Software development
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides patterns and templates for integrating Azure Cosmos DB into Python and FastAPI applications. It focuses on secure authentication using DefaultAzureCredential, singleton client management, and service layer patterns for CRUD operations. The guidance includes strategies for partition key management, parameterized queries, and TDD-based testing using pytest.
What it does
- Provides a singleton pattern for Cosmos DB client initialization.
- Implements dual authentication for local emulator and Azure production environments.
- Wraps synchronous SDK calls for asynchronous execution in FastAPI.
- Defines a service layer pattern for document-to-model conversion.
- Offers templates for pytest fixtures to facilitate unit testing.
- Outlines error handling patterns for common Cosmos DB exceptions.
When to use it
- When building a FastAPI backend that requires NoSQL persistence with Azure Cosmos DB.
- When you need to implement secure, RBAC-based authentication for database access.
- When you want to structure your database interaction layer using service classes.
- When you need to write unit tests for code that interacts with the Cosmos DB SDK.
Advantages
- Promotes secure coding by using identity-based authentication instead of hardcoded keys.
- Ensures consistent connection management through singleton patterns.
- Facilitates testability by providing patterns for mocking database containers.
- Encourages clean code through separation of concerns between business logic and storage.
Usage examples
- “How do I set up a singleton Cosmos DB client in my FastAPI app?”
- The skill provides a module-level initialization pattern that uses DefaultAzureCredential for production and key-based auth for the local emulator.
- “Show me how to test a service layer method that reads from Cosmos DB.”
- The skill provides a pytest fixture template that uses mocking to simulate the Cosmos container, allowing you to test service logic without a live database.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/microsoft/azure-cosmos-db-py/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip azure-cosmos-db-py.zip -d .agents/skills
Documentation by Microsoft
Cosmos DB Service Implementation
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
Installation
pip install azure-cosmos azure-identityEnvironment Variables
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/ # Required for all auth methods
COSMOS_DATABASE_NAME=<database-name> # Required for all auth methods
COSMOS_CONTAINER_ID=<container-id> # Required for all auth methods
# For emulator only (not production)
COSMOS_KEY=<emulator-key> # Only required for key-based auth or emulator
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in productionAuthentication & Lifecycle
🔑 Two rules apply to every code sample below:
Prefer
DefaultAzureCredential. It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
Local dev:
DefaultAzureCredentialworks as-is.Production: set
AZURE_TOKEN_CREDENTIALS=prod(orAZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.Wrap every client in a context manager so HTTP transports, sockets, and token caches are released deterministically:
Sync:
with <Client>(...) as client:Async:
async with <Client>(...) as client:andasync with DefaultAzureCredential() as credential:(fromazure.identity.aio)Snippets may abbreviate this setup, but production code should always follow both rules.
DefaultAzureCredential (preferred):
import os
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
with CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=credential
) as client:
# Use client here (see following sections for operations)
...Emulator (local development):
from azure.cosmos import CosmosClient
with CosmosClient(
url="https://localhost:8081",
credential=os.environ["COSMOS_KEY"],
connection_verify=False
) as client:
# Use client here (see following sections for operations)
...Architecture Overview
┌─────────────────────────────────────────────────────────────────┐
│ FastAPI Router │
│ - Auth dependencies (get_current_user, get_current_user_required)
│ - HTTP error responses (HTTPException) │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Service Layer │
│ - Business logic and validation │
│ - Document ↔ Model conversion │
│ - Graceful degradation when Cosmos unavailable │
└──────────────────────────────┬──────────────────────────────────┘
│
┌──────────────────────────────▼──────────────────────────────────┐
│ Cosmos DB Client Module │
│ - Singleton container initialization │
│ - Dual auth: DefaultAzureCredential (Azure) / Key (emulator) │
│ - Async wrapper via run_in_threadpool │
└─────────────────────────────────────────────────────────────────┘Quick Start
1. Client Module Setup
Create a singleton Cosmos client with dual authentication:
# db/cosmos.py
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
from starlette.concurrency import run_in_threadpool
_cosmos_container = None
def _is_emulator_endpoint(endpoint: str) -> bool:
return "localhost" in endpoint or "127.0.0.1" in endpoint
async def get_container():
global _cosmos_container
if _cosmos_container is None:
# Singleton: client lives for the FastAPI app lifetime; close in a lifespan shutdown handler.
if _is_emulator_endpoint(settings.cosmos_endpoint):
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=settings.cosmos_key,
connection_verify=False
)
else:
client = CosmosClient(
url=settings.cosmos_endpoint,
credential=DefaultAzureCredential()
)
db = client.get_database_client(settings.cosmos_database_name)
_cosmos_container = db.get_container_client(settings.cosmos_container_id)
return _cosmos_containerFull implementation: See references/client-setup.md
2. Pydantic Model Hierarchy
Use five-tier model pattern for clean separation:
class ProjectBase(BaseModel): # Shared fields
name: str = Field(..., min_length=1, max_length=200)
class ProjectCreate(ProjectBase): # Creation request
workspace_id: str = Field(..., alias="workspaceId")
class ProjectUpdate(BaseModel): # Partial updates (all optional)
name: Optional[str] = Field(None, min_length=1)
class Project(ProjectBase): # API response
id: str
created_at: datetime = Field(..., alias="createdAt")
class ProjectInDB(Project): # Internal with docType
doc_type: str = "project"3. Service Layer Pattern
class ProjectService:
def _use_cosmos(self) -> bool:
return get_container() is not None
async def get_by_id(self, project_id: str, workspace_id: str) -> Project | None:
if not self._use_cosmos():
return None
doc = await get_document(project_id, partition_key=workspace_id)
if doc is None:
return None
return self._doc_to_model(doc)Full patterns: See references/service-layer.md
Core Principles
Security Requirements
RBAC Authentication: Use
DefaultAzureCredentialin Azure — never store keys in codeEmulator-Only Keys: Hardcode the well-known emulator key only for local development
Parameterized Queries: Always use
@parametersyntax — never string concatenationPartition Key Validation: Validate partition key access matches user authorization
Clean Code Conventions
Single Responsibility: Client module handles connection; services handle business logic
Graceful Degradation: Services return
None/[]when Cosmos unavailableConsistent Naming:
_doc_to_model(),_model_to_doc(),_use_cosmos()Type Hints: Full typing on all public methods
CamelCase Aliases: Use
Field(alias="camelCase")for JSON serialization
TDD Requirements
Write tests BEFORE implementation using these patterns:
@pytest.fixture
def mock_cosmos_container(mocker):
container = mocker.MagicMock()
mocker.patch("app.db.cosmos.get_container", return_value=container)
return container
@pytest.mark.asyncio
async def test_get_project_by_id_returns_project(mock_cosmos_container):
# Arrange
mock_cosmos_container.read_item.return_value = {"id": "123", "name": "Test"}
# Act
result = await project_service.get_by_id("123", "workspace-1")
# Assert
assert result.id == "123"
assert result.name == "Test"Full testing guide: See references/testing.md
Best Practices
Pick sync OR async and stay consistent. Do not mix
azure.xxxsync clients withazure.xxx.aioasync clients in the same call path. Choose one mode per module.Always use context managers for clients and async credentials. Wrap the client in
async with CosmosClient(...) as client:(or manage its lifetime via FastAPI lifespan and close it explicitly). For asyncDefaultAzureCredentialfromazure.identity.aio, also useasync with credential:so tokens and transports are cleaned up.
Reference Files
| File | When to Read |
|---|---|
| references/client-setup.md | Setting up Cosmos client with dual auth, SSL config, singleton pattern |
| references/service-layer.md | Implementing full service class with CRUD, conversions, graceful degradation |
| references/testing.md | Writing pytest tests, mocking Cosmos, integration test setup |
| references/partitioning.md | Choosing partition keys, cross-partition queries, move operations |
| references/error-handling.md | Handling CosmosResourceNotFoundError, logging, HTTP error mapping |
Template Files
| File | Purpose |
|---|---|
| assets/cosmos_client_template.py | Ready-to-use client module |
| assets/service_template.py | Service class skeleton |
| assets/conftest_template.py | pytest fixtures for Cosmos mocking |
Quality Attributes (NFRs)
Reliability
Graceful degradation when Cosmos unavailable
Retry logic with exponential backoff for transient failures
Connection pooling via singleton pattern
Security
Zero secrets in code (RBAC via DefaultAzureCredential)
Parameterized queries prevent injection
Partition key isolation enforces data boundaries
Maintainability
Five-tier model pattern enables schema evolution
Service layer decouples business logic from storage
Consistent patterns across all entity services
Testability
Dependency injection via
get_container()Easy mocking with module-level globals
Clear separation enables unit testing without Cosmos
Performance
Partition key queries avoid cross-partition scans
Async wrapping prevents blocking FastAPI event loop
Minimal document conversion overhead
Files
- ATTRIBUTION.mdAdded by AutoGineer965 B
- LICENSELicence file added by AutoGineer1.1 KiB
- SKILL.md11.6 KiB
- assets/conftest_template.pyScript9.7 KiB
- assets/cosmos_client_template.pyScript6.2 KiB
- assets/service_template.pyScript9.2 KiB
- references/client-setup.md6.1 KiB
- references/error-handling.md10.3 KiB
- references/partitioning.md7.2 KiB
- references/service-layer.md8.2 KiB
- references/testing.md14.3 KiB
references/service-layer.md
Service Layer Pattern
Table of Contents
Service Class Structure
Document Conversion Methods
CRUD Operations
Query Patterns
Graceful Degradation
Complete Example
Service Class Structure
Every service follows this pattern:
from typing import Optional
from app.db.cosmos import get_container, upsert_document, get_document, delete_document, query_documents
from app.models.project import Project, ProjectCreate, ProjectUpdate, ProjectInDB
class ProjectService:
"""Service for project CRUD operations."""
def _use_cosmos(self) -> bool:
"""Check if Cosmos is available."""
return get_container() is not None
# Document conversion methods
def _doc_to_model_in_db(self, doc: dict) -> ProjectInDB:
"""Convert Cosmos document to internal model."""
...
def _model_in_db_to_doc(self, model: ProjectInDB) -> dict:
"""Convert internal model to Cosmos document."""
...
def _model_in_db_to_model(self, model_in_db: ProjectInDB) -> Project:
"""Convert internal model to API response model."""
...
# CRUD operations
async def create(self, data: ProjectCreate, author_id: str) -> Project:
...
async def get_by_id(self, project_id: str, workspace_id: str) -> Optional[Project]:
...
async def update(self, project_id: str, workspace_id: str, data: ProjectUpdate) -> Optional[Project]:
...
async def delete(self, project_id: str, workspace_id: str) -> bool:
...
async def list_by_workspace(self, workspace_id: str) -> list[Project]:
...
# Singleton instance
project_service = ProjectService()Document Conversion Methods
Document → Model (from Cosmos)
def _doc_to_model_in_db(self, doc: dict) -> ProjectInDB:
"""Convert Cosmos document to ProjectInDB."""
return ProjectInDB(
id=doc["id"],
name=doc["name"],
description=doc.get("description"),
slug=doc["slug"],
workspace_id=doc["workspaceId"],
author_id=doc["authorId"],
visibility=doc.get("visibility", "public"),
tags=doc.get("tags", []),
created_at=datetime.fromisoformat(doc["createdAt"]),
updated_at=datetime.fromisoformat(doc["updatedAt"]) if doc.get("updatedAt") else None,
doc_type=doc.get("docType", "project"),
)Model → Document (to Cosmos)
def _model_in_db_to_doc(self, model: ProjectInDB) -> dict:
"""Convert ProjectInDB to Cosmos document."""
return {
"id": model.id,
"name": model.name,
"description": model.description,
"slug": model.slug,
"workspaceId": model.workspace_id, # Partition key
"authorId": model.author_id,
"visibility": model.visibility,
"tags": model.tags,
"createdAt": model.created_at.isoformat(),
"updatedAt": model.updated_at.isoformat() if model.updated_at else None,
"docType": model.doc_type,
}InDB → Response (strip internal fields)
def _model_in_db_to_model(self, model_in_db: ProjectInDB) -> Project:
"""Convert ProjectInDB to API response model."""
return Project(
id=model_in_db.id,
name=model_in_db.name,
description=model_in_db.description,
slug=model_in_db.slug,
workspace_id=model_in_db.workspace_id,
author_id=model_in_db.author_id,
visibility=model_in_db.visibility,
tags=model_in_db.tags,
created_at=model_in_db.created_at,
updated_at=model_in_db.updated_at,
)CRUD Operations
Create
async def create(self, data: ProjectCreate, author_id: str) -> Project:
"""Create a new project."""
if not self._use_cosmos():
raise RuntimeError("Database unavailable")
now = datetime.now(timezone.utc)
slug = await self._generate_unique_slug(data.name, data.workspace_id)
project_in_db = ProjectInDB(
id=str(uuid.uuid4()),
name=data.name,
description=data.description,
slug=slug,
workspace_id=data.workspace_id,
author_id=author_id,
visibility=data.visibility,
tags=data.tags,
created_at=now,
updated_at=None,
doc_type="project",
)
doc = self._model_in_db_to_doc(project_in_db)
await upsert_document(doc, partition_key=data.workspace_id)
return self._model_in_db_to_model(project_in_db)Read (Get by ID)
async def get_by_id(self, project_id: str, workspace_id: str) -> Optional[Project]:
"""Get project by ID. Returns None if not found."""
if not self._use_cosmos():
return None
doc = await get_document(project_id, partition_key=workspace_id)
if doc is None:
return None
model_in_db = self._doc_to_model_in_db(doc)
return self._model_in_db_to_model(model_in_db)Update
async def update(
self, project_id: str, workspace_id: str, data: ProjectUpdate
) -> Optional[Project]:
"""Update project. Returns None if not found."""
if not self._use_cosmos():
return None
doc = await get_document(project_id, partition_key=workspace_id)
if doc is None:
return None
model_in_db = self._doc_to_model_in_db(doc)
# Apply updates (only non-None fields)
update_data = data.model_dump(exclude_unset=True)
for field, value in update_data.items():
if hasattr(model_in_db, field):
setattr(model_in_db, field, value)
model_in_db.updated_at = datetime.now(timezone.utc)
updated_doc = self._model_in_db_to_doc(model_in_db)
await upsert_document(updated_doc, partition_key=workspace_id)
return self._model_in_db_to_model(model_in_db)Delete
async def delete(self, project_id: str, workspace_id: str) -> bool:
"""Delete project. Returns True if deleted."""
if not self._use_cosmos():
return False
return await delete_document(project_id, partition_key=workspace_id)List
async def list_by_workspace(self, workspace_id: str) -> list[Project]:
"""List all projects in a workspace."""
if not self._use_cosmos():
return []
docs = await query_documents(
doc_type="project",
partition_key=workspace_id,
)
return [
self._model_in_db_to_model(self._doc_to_model_in_db(doc))
for doc in docs
]Query Patterns
Basic Query with Filter
async def get_by_slug(self, slug: str, workspace_id: str) -> Optional[Project]:
"""Get project by slug within a workspace."""
docs = await query_documents(
doc_type="project",
partition_key=workspace_id,
extra_filter="AND c.slug = @slug",
parameters=[{"name": "@slug", "value": slug}],
)
if not docs:
return None
return self._model_in_db_to_model(self._doc_to_model_in_db(docs[0]))Unique Slug Generation
async def _generate_unique_slug(self, name: str, workspace_id: str) -> str:
"""Generate unique slug from name."""
base_slug = slugify(name)
slug = base_slug
counter = 1
while True:
existing = await query_documents(
doc_type="project",
partition_key=workspace_id,
extra_filter="AND c.slug = @slug",
parameters=[{"name": "@slug", "value": slug}],
)
if not existing:
return slug
slug = f"{base_slug}-{counter}"
counter += 1Graceful Degradation
Every public method checks _use_cosmos() and returns safe defaults:
| Return Type | Default |
|---|---|
Optional[Model] | None |
list[Model] | [] |
bool | False |
| Required create | raise RuntimeError |
async def get_by_id(self, project_id: str, workspace_id: str) -> Optional[Project]:
if not self._use_cosmos():
return None # Graceful None instead of exception
...Complete Example
See assets/service_template.py for a production-ready service implementation.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs an API key, Needs Python
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- Microsoft
- Publisher
- Microsoft (Official)
- Source
- microsoft/skills · .github/plugins/azure-sdk-python/skills/azure-cosmos-db-py · commit 0696600
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Microsoft.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download azure-cosmos-db-py.zip