Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
.claude/skills/azure-cosmos-db-py/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-07 | ✗→✓ | ▲ Improved | — | — |
| case-10 | ✗→✓ | ▲ Improved | — | — |
| case-01 | ✗→✓ | ▲ Improved | — | — |
| case-09 | ✗→✓ | ▲ Improved | — | — |
| case-15 | ✗→✓ | ▲ Improved | — | — |
Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
bashpip install azure-cosmos azure-identity
bashCOSMOS_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>
DefaultAzureCredential (preferred):
pythonfrom azure.cosmos import CosmosClient from azure.identity import DefaultAzureCredential client = CosmosClient( url=os.environ["COSMOS_ENDPOINT"], credential=DefaultAzureCredential() )
Emulator (local development):
pythonfrom azure.cosmos import CosmosClient client = CosmosClient( url="https://localhost:8081", credential=os.environ["COSMOS_KEY"], connection_verify=False )
┌─────────────────────────────────────────────────────────────────┐
│ 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 │
└─────────────────────────────────────────────────────────────────┘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
Use five-tier model pattern for clean separation:
pythonclass 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"
pythonclass 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
DefaultAzureCredential in Azure — never store keys in code@parameter syntax — never string concatenationNone/[] when Cosmos unavailable_doc_to_model(), _model_to_doc(), _use_cosmos()Field(alias="camelCase") for JSON serializationWrite 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
| 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 |
| 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 |
get_container()This skill is applicable to execute the workflow or actions described in the overview.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-12 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-16 | pass→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-22 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-07 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-06 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-17 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-10 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-18 | pass→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-20 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-14 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-08 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-05 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-11 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-21 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-01 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-13 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-03 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-09 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-15 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-04 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-02 | fail→pass | — | — | — | — | — | — | — | — | — | — | — | — |
case-19 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
case-23 | fail→fail | — | — | — | — | — | — | — | — | — | — | — | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 23 cases were attempted. The headline lift of +22 percentage points is the difference between those two pass rates over the 23 comparable cases. 1 case got worse with the skill loaded, and it is included in that figure.
The per-case answers from this run were removed by the retention sweep, so the case table below shows the verdicts without the text either arm produced. The counts above were recorded at the time and are unaffected. Answers are now kept for 180 days.
Other measured skills in the registry, with their headline benchmark lift.