azure-cosmos-db-py
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
About this skill
This skill empowers an AI agent to guide developers in building robust Azure Cosmos DB NoSQL services using Python. It incorporates best practices for clean code, security, and Test-Driven Development (TDD). The AI can leverage this skill to generate code snippets, suggest architectural patterns, or provide comprehensive setup instructions, ensuring the resulting services are production-grade and maintainable. It details necessary Python libraries (`azure-cosmos`, `azure-identity`), environment variable configurations, and preferred authentication methods like `DefaultAzureCredential` for secure access.
Best use case
When a developer needs assistance in writing Python code for Azure Cosmos DB, requiring adherence to specific coding standards, security protocols, or TDD methodology. Ideal for bootstrapping new Cosmos DB integrations, refactoring existing ones with best practices in mind, or generating boilerplate code for data access layers.
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
Well-structured, secure, and testable Python code for interacting with Azure Cosmos DB, along with clear instructions for environment setup and authentication. The generated code will reflect clean code principles, security considerations, and TDD-friendly design.
Practical example
Example input
Generate Python code for an Azure Cosmos DB service that manages user profiles. The code should adhere to clean code, security best practices, and TDD principles. Provide instructions for environment variables and preferred authentication methods.
Example output
```python
# Example AI-generated output based on the skill
# --- Installation Instructions ---
# Install necessary Python libraries:
# pip install azure-cosmos azure-identity
# --- Environment Variables (example for .env file or direct setup) ---
# COSMOS_ENDPOINT=https://<your-cosmosdb-account-name>.documents.azure.com:443/
# COSMOS_DATABASE_NAME=UserProfileDB
# COSMOS_CONTAINER_ID=Users
# # For local emulator only (do NOT use in production with DefaultAzureCredential)
# # COSMOS_KEY=<your-emulator-primary-key>
# --- Python UserProfileService Implementation ---
import os
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential, ClientSecretCredential
class UserProfileService:
def __init__(self):
self.endpoint = os.environ.get("COSMOS_ENDPOINT")
self.database_name = os.environ.get("COSMOS_DATABASE_NAME")
self.container_id = os.environ.get("COSMOS_CONTAINER_ID")
if not all([self.endpoint, self.database_name, self.container_id]):
raise ValueError("Missing one or more Cosmos DB environment variables.")
# Preferred authentication: DefaultAzureCredential (for managed identities, VS Code, Azure CLI, etc.)
# Fallback to key for local development/emulator if COSMOS_KEY is set and endpoint is local
cosmos_key = os.environ.get("COSMOS_KEY")
if cosmos_key and "localhost" in self.endpoint:
self.client = CosmosClient(self.endpoint, cosmos_key)
else:
# For production/cloud environments, DefaultAzureCredential is recommended
# Ensure your environment is configured for Azure authentication (e.g., Azure CLI logged in)
credential = DefaultAzureCredential()
self.client = CosmosClient(self.endpoint, credential)
self.database = self.client.get_database_client(self.database_name)
self.container = self.database.get_container_client(self.container_id)
def create_user(self, user_data: dict) -> dict:
"""Creates a new user profile in Cosmos DB."""
# Security: Input validation and sanitization should be performed upstream
# TDD: This method should be unit-testable without actual DB interaction initially
if "id" not in user_data:
# Cosmos DB can auto-generate IDs, or provide one explicitly
user_data["id"] = str(uuid.uuid4()) # Example for UUID generation
return self.container.create_item(body=user_data, enable_automatic_id_generation=False)
def get_user_by_id(self, user_id: str, partition_key_value: str = None) -> dict:
"""Retrieves a user profile by ID, optionally with a partition key."""
try:
if partition_key_value:
return self.container.read_item(item=user_id, partition_key=partition_key_value)
else:
# For containers with a logical partition key, querying across partitions might be expensive.
# Prefer providing the partition_key_value if known.
query = f"SELECT * FROM c WHERE c.id = '{user_id}'"
items = list(self.container.query_items(query=query, enable_cross_partition_query=True))
return items[0] if items else None
except Exception as e:
print(f"Error retrieving user {user_id}: {e}")
return None
def update_user(self, user_id: str, updated_data: dict, partition_key_value: str) -> dict:
"""Updates an existing user profile."""
# Ensure 'id' and partition key are correctly handled for updates
updated_data["id"] = user_id
return self.container.upsert_item(body=updated_data, partition_key=partition_key_value)
def delete_user(self, user_id: str, partition_key_value: str):
"""Deletes a user profile."""
self.container.delete_item(item=user_id, partition_key=partition_key_value)
print(f"User {user_id} deleted.")
# Example Usage (typically for integration tests or main entry point)
if __name__ == "__main__":
try:
service = UserProfileService()
# Further code to test or use the service
print("Cosmos DB Service initialized successfully.")
except ValueError as ve:
print(f"Configuration Error: {ve}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
```When to use this skill
- Use this skill when you need to develop a new service interacting with Azure Cosmos DB and want to ensure it follows industry best practices from the start. It's also valuable for generating boilerplate code, setting up secure connections, or understanding how to structure Cosmos DB operations in a TDD-friendly manner, particularly for NoSQL models.
When not to use this skill
- Do not use this skill if you are looking for an AI to directly perform CRUD operations on an existing Cosmos DB instance without involving code generation or development assistance. This skill focuses on *building* the underlying services and code, not on directly *operating* a deployed Cosmos DB for end-user tasks.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/azure-cosmos-db-py/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How azure-cosmos-db-py Compares
| Feature / Agent | azure-cosmos-db-py | Standard Approach |
|---|---|---|
| Platform Support | Claude | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | medium | N/A |
Frequently Asked Questions
What does this skill do?
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
Which AI agents support this skill?
This skill is designed for Claude.
How difficult is it to install?
The installation complexity is rated as medium. You can find the installation instructions above.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Cosmos DB Service Implementation
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
## Installation
```bash
pip install azure-cosmos azure-identity
```
## Environment Variables
```bash
COSMOS_ENDPOINT=https://<account>.documents.azure.com:443/
COSMOS_DATABASE_NAME=<database-name>
COSMOS_CONTAINER_ID=<container-id>
# For emulator only (not production)
COSMOS_KEY=<emulator-key>
```
## Authentication
**DefaultAzureCredential (preferred)**:
```python
from azure.cosmos import CosmosClient
from azure.identity import DefaultAzureCredential
client = CosmosClient(
url=os.environ["COSMOS_ENDPOINT"],
credential=DefaultAzureCredential()
)
```
**Emulator (local development)**:
```python
from azure.cosmos import CosmosClient
client = CosmosClient(
url="https://localhost:8081",
credential=os.environ["COSMOS_KEY"],
connection_verify=False
)
```
## 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:
```python
# 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:
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_container
```
**Full implementation**: See references/client-setup.md
### 2. Pydantic Model Hierarchy
Use five-tier model pattern for clean separation:
```python
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
```python
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
1. **RBAC Authentication**: Use `DefaultAzureCredential` in Azure — never store keys in code
2. **Emulator-Only Keys**: Hardcode the well-known emulator key only for local development
3. **Parameterized Queries**: Always use `@parameter` syntax — never string concatenation
4. **Partition Key Validation**: Validate partition key access matches user authorization
### Clean Code Conventions
1. **Single Responsibility**: Client module handles connection; services handle business logic
2. **Graceful Degradation**: Services return `None`/`[]` when Cosmos unavailable
3. **Consistent Naming**: `_doc_to_model()`, `_model_to_doc()`, `_use_cosmos()`
4. **Type Hints**: Full typing on all public methods
5. **CamelCase Aliases**: Use `Field(alias="camelCase")` for JSON serialization
### TDD Requirements
Write tests BEFORE implementation using these patterns:
```python
@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
## 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
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.Related Skills
azure-cosmos-rust
Azure Cosmos DB SDK for Rust (NoSQL API). Use for document CRUD, queries, containers, and globally distributed data.
azure-cosmos-py
Azure Cosmos DB SDK for Python (NoSQL API). Use for document CRUD, queries, containers, and globally distributed data.
database-optimizer
Expert database optimizer specializing in modern performance tuning, query optimization, and scalable architectures.
database-migrations-sql-migrations
SQL database migrations with zero-downtime strategies for PostgreSQL, MySQL, and SQL Server. Focus on data integrity and rollback plans.
database-migration
Master database schema and data migrations across ORMs (Sequelize, TypeORM, Prisma), including rollback strategies and zero-downtime deployments.
claimable-postgres
Provision instant temporary Postgres databases via Claimable Postgres by Neon (pg.new). No login or credit card required. Use for quick Postgres environments and throwaway DATABASE_URL for prototyping.
microsoft-azure-webjobs-extensions-authentication-events-dotnet
Microsoft Entra Authentication Events SDK for .NET. Azure Functions triggers for custom authentication extensions.
azure-web-pubsub-ts
Real-time messaging with WebSocket connections and pub/sub patterns.
azure-storage-queue-ts
Azure Queue Storage JavaScript/TypeScript SDK (@azure/storage-queue) for message queue operations. Use for sending, receiving, peeking, and deleting messages in queues.
azure-storage-queue-py
Azure Queue Storage SDK for Python. Use for reliable message queuing, task distribution, and asynchronous processing.
azure-storage-file-share-ts
Azure File Share JavaScript/TypeScript SDK (@azure/storage-file-share) for SMB file share operations.
azure-storage-file-share-py
Azure Storage File Share SDK for Python. Use for SMB file shares, directories, and file operations in the cloud.