{"id":"ccf3fa8e-e975-4208-94e7-1b356160c758","shortId":"yff3BG","kind":"skill","title":"azure-cosmos-db-py","tagline":"Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.","description":"# Cosmos DB Service Implementation\n\nBuild production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.\n\n## Installation\n\n```bash\npip install azure-cosmos azure-identity\n```\n\n## Environment Variables\n\n```bash\nCOSMOS_ENDPOINT=https://<account>.documents.azure.com:443/\nCOSMOS_DATABASE_NAME=<database-name>\nCOSMOS_CONTAINER_ID=<container-id>\n# For emulator only (not production)\nCOSMOS_KEY=<emulator-key>\n```\n\n## Authentication\n\n**DefaultAzureCredential (preferred)**:\n```python\nfrom azure.cosmos import CosmosClient\nfrom azure.identity import DefaultAzureCredential\n\nclient = CosmosClient(\n    url=os.environ[\"COSMOS_ENDPOINT\"],\n    credential=DefaultAzureCredential()\n)\n```\n\n**Emulator (local development)**:\n```python\nfrom azure.cosmos import CosmosClient\n\nclient = CosmosClient(\n    url=\"https://localhost:8081\",\n    credential=os.environ[\"COSMOS_KEY\"],\n    connection_verify=False\n)\n```\n\n## Architecture Overview\n\n```\n┌─────────────────────────────────────────────────────────────────┐\n│                         FastAPI Router                          │\n│  - Auth dependencies (get_current_user, get_current_user_required)\n│  - HTTP error responses (HTTPException)                         │\n└──────────────────────────────┬──────────────────────────────────┘\n                               │\n┌──────────────────────────────▼──────────────────────────────────┐\n│                        Service Layer                            │\n│  - Business logic and validation                                │\n│  - Document ↔ Model conversion                                  │\n│  - Graceful degradation when Cosmos unavailable                 │\n└──────────────────────────────┬──────────────────────────────────┘\n                               │\n┌──────────────────────────────▼──────────────────────────────────┐\n│                     Cosmos DB Client Module                     │\n│  - Singleton container initialization                           │\n│  - Dual auth: DefaultAzureCredential (Azure) / Key (emulator)   │\n│  - Async wrapper via run_in_threadpool                          │\n└─────────────────────────────────────────────────────────────────┘\n```\n\n## Quick Start\n\n### 1. Client Module Setup\n\nCreate a singleton Cosmos client with dual authentication:\n\n```python\n# db/cosmos.py\nfrom azure.cosmos import CosmosClient\nfrom azure.identity import DefaultAzureCredential\nfrom starlette.concurrency import run_in_threadpool\n\n_cosmos_container = None\n\ndef _is_emulator_endpoint(endpoint: str) -> bool:\n    return \"localhost\" in endpoint or \"127.0.0.1\" in endpoint\n\nasync def get_container():\n    global _cosmos_container\n    if _cosmos_container is None:\n        if _is_emulator_endpoint(settings.cosmos_endpoint):\n            client = CosmosClient(\n                url=settings.cosmos_endpoint,\n                credential=settings.cosmos_key,\n                connection_verify=False\n            )\n        else:\n            client = CosmosClient(\n                url=settings.cosmos_endpoint,\n                credential=DefaultAzureCredential()\n            )\n        db = client.get_database_client(settings.cosmos_database_name)\n        _cosmos_container = db.get_container_client(settings.cosmos_container_id)\n    return _cosmos_container\n```\n\n**Full implementation**: See references/client-setup.md\n\n### 2. Pydantic Model Hierarchy\n\nUse five-tier model pattern for clean separation:\n\n```python\nclass ProjectBase(BaseModel):           # Shared fields\n    name: str = Field(..., min_length=1, max_length=200)\n\nclass ProjectCreate(ProjectBase):       # Creation request\n    workspace_id: str = Field(..., alias=\"workspaceId\")\n\nclass ProjectUpdate(BaseModel):         # Partial updates (all optional)\n    name: Optional[str] = Field(None, min_length=1)\n\nclass Project(ProjectBase):             # API response\n    id: str\n    created_at: datetime = Field(..., alias=\"createdAt\")\n\nclass ProjectInDB(Project):             # Internal with docType\n    doc_type: str = \"project\"\n```\n\n### 3. Service Layer Pattern\n\n```python\nclass ProjectService:\n    def _use_cosmos(self) -> bool:\n        return get_container() is not None\n    \n    async def get_by_id(self, project_id: str, workspace_id: str) -> Project | None:\n        if not self._use_cosmos():\n            return None\n        doc = await get_document(project_id, partition_key=workspace_id)\n        if doc is None:\n            return None\n        return self._doc_to_model(doc)\n```\n\n**Full patterns**: See references/service-layer.md\n\n## Core Principles\n\n### Security Requirements\n\n1. **RBAC Authentication**: Use `DefaultAzureCredential` in Azure — never store keys in code\n2. **Emulator-Only Keys**: Hardcode the well-known emulator key only for local development\n3. **Parameterized Queries**: Always use `@parameter` syntax — never string concatenation\n4. **Partition Key Validation**: Validate partition key access matches user authorization\n\n### Clean Code Conventions\n\n1. **Single Responsibility**: Client module handles connection; services handle business logic\n2. **Graceful Degradation**: Services return `None`/`[]` when Cosmos unavailable\n3. **Consistent Naming**: `_doc_to_model()`, `_model_to_doc()`, `_use_cosmos()`\n4. **Type Hints**: Full typing on all public methods\n5. **CamelCase Aliases**: Use `Field(alias=\"camelCase\")` for JSON serialization\n\n### TDD Requirements\n\nWrite tests BEFORE implementation using these patterns:\n\n```python\n@pytest.fixture\ndef mock_cosmos_container(mocker):\n    container = mocker.MagicMock()\n    mocker.patch(\"app.db.cosmos.get_container\", return_value=container)\n    return container\n\n@pytest.mark.asyncio\nasync def test_get_project_by_id_returns_project(mock_cosmos_container):\n    # Arrange\n    mock_cosmos_container.read_item.return_value = {\"id\": \"123\", \"name\": \"Test\"}\n    \n    # Act\n    result = await project_service.get_by_id(\"123\", \"workspace-1\")\n    \n    # Assert\n    assert result.id == \"123\"\n    assert result.name == \"Test\"\n```\n\n**Full testing guide**: See references/testing.md\n\n## Reference Files\n\n| File | When to Read |\n|------|--------------|\n| references/client-setup.md | Setting up Cosmos client with dual auth, SSL config, singleton pattern |\n| references/service-layer.md | Implementing full service class with CRUD, conversions, graceful degradation |\n| references/testing.md | Writing pytest tests, mocking Cosmos, integration test setup |\n| references/partitioning.md | Choosing partition keys, cross-partition queries, move operations |\n| references/error-handling.md | Handling CosmosResourceNotFoundError, logging, HTTP error mapping |\n\n## Template Files\n\n| File | Purpose |\n|------|---------|\n| assets/cosmos_client_template.py | Ready-to-use client module |\n| assets/service_template.py | Service class skeleton |\n| assets/conftest_template.py | pytest fixtures for Cosmos mocking |\n\n## Quality Attributes (NFRs)\n\n### Reliability\n- Graceful degradation when Cosmos unavailable\n- Retry logic with exponential backoff for transient failures\n- Connection pooling via singleton pattern\n\n### Security\n- Zero secrets in code (RBAC via DefaultAzureCredential)\n- Parameterized queries prevent injection\n- Partition key isolation enforces data boundaries\n\n### Maintainability\n- Five-tier model pattern enables schema evolution\n- Service layer decouples business logic from storage\n- Consistent patterns across all entity services\n\n### Testability\n- Dependency injection via `get_container()`\n- Easy mocking with module-level globals\n- Clear separation enables unit testing without Cosmos\n\n### Performance\n- Partition key queries avoid cross-partition scans\n- Async wrapping prevents blocking FastAPI event loop\n- Minimal document conversion overhead\n\n## When to Use\nThis skill is applicable to execute the workflow or actions described in the overview.\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.","tags":["azure","cosmos","antigravity","awesome","skills","sickn33","agent-skills","agentic-skills","ai-agent-skills","ai-agents","ai-coding","ai-workflows"],"capabilities":["skill","source-sickn33","skill-azure-cosmos-db-py","topic-agent-skills","topic-agentic-skills","topic-ai-agent-skills","topic-ai-agents","topic-ai-coding","topic-ai-workflows","topic-antigravity","topic-antigravity-skills","topic-claude-code","topic-claude-code-skills","topic-codex-cli","topic-codex-skills"],"categories":["antigravity-awesome-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/sickn33/antigravity-awesome-skills/azure-cosmos-db-py","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add sickn33/antigravity-awesome-skills","source_repo":"https://github.com/sickn33/antigravity-awesome-skills","install_from":"skills.sh"}},"qualityScore":"0.700","qualityRationale":"deterministic score 0.70 from registry signals: · indexed on github topic:agent-skills · 34928 github stars · SKILL.md body (8,136 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-04-24T18:50:29.757Z","embedding":null,"createdAt":"2026-04-18T21:32:16.983Z","updatedAt":"2026-04-24T18:50:29.757Z","lastSeenAt":"2026-04-24T18:50:29.757Z","tsv":"'-1':569 '1':167,296,325,413,465 '123':558,567,573 '127.0.0.1':210 '2':272,425,476 '200':299 '3':349,441,485 '4':451,496 '5':505 '8081':107 'access':458 'across':715 'act':561 'action':771 'alia':309,337,510 'alias':507 'alway':444 'api':329 'app.db.cosmos.get':534 'applic':765 'architectur':115 'arrang':554 'ask':809 'assert':570,571,574 'assets/conftest_template.py':651 'assets/cosmos_client_template.py':640 'assets/service_template.py':647 'async':159,213,367,542,748 'attribut':658 'auth':119,154,595 'authent':75,178,415 'author':461 'avoid':743 'await':387,563 'azur':2,10,32,51,54,156,419 'azure-cosmo':50 'azure-cosmos-db-pi':1 'azure-ident':53 'azure.cosmos':80,100,182 'azure.identity':84,186 'backoff':670 'basemodel':288,313 'bash':47,58 'best':19,41 'block':751 'bool':204,360 'boundari':696,817 'build':6,28 'busi':134,474,709 'camelcas':506,511 'choos':620 'clarif':811 'class':286,300,311,326,339,354,604,649 'clean':16,38,283,462 'clear':732,784 'client':87,103,148,168,175,231,243,253,261,468,592,645 'client.get':251 'code':17,39,424,463,683 'concaten':450 'config':597 'connect':112,239,471,674 'consist':486,713 'contain':66,151,196,216,219,222,258,260,263,267,363,529,531,535,538,540,553,724 'convent':464 'convers':140,607,757 'core':409 'cosmos':3,11,24,33,52,59,62,65,73,91,110,144,146,174,195,218,221,257,266,358,483,495,528,552,591,615,655,664,738 'cosmoscli':82,88,102,104,184,232,244 'cosmosresourcenotfounderror':631 'creat':171,333 'createdat':338 'creation':303 'credenti':93,108,236,248 'criteria':820 'cross':624,745 'cross-partit':623,744 'crud':606 'current':122,125 'data':695 'databas':63,252,255 'datetim':335 'db':4,12,25,34,147,250 'db.get':259 'db/cosmos.py':180 'decoupl':708 'def':198,214,356,368,526,543 'defaultazurecredenti':76,86,94,155,188,249,417,686 'degrad':142,478,609,662 'depend':120,720 'describ':772,788 'develop':97,440 'doc':345,386,397,404,488,493 'doctyp':344 'document':138,389,756 'documents.azure.com:443':61 'dual':153,177,594 'easi':725 'els':242 'emul':69,95,158,200,227,427,435 'emulator-on':426 'enabl':703,734 'endpoint':60,92,201,202,208,212,228,230,235,247 'enforc':694 'entiti':717 'environ':56,800 'environment-specif':799 'error':129,634 'event':753 'evolut':705 'execut':767 'expert':805 'exponenti':669 'failur':673 'fals':114,241 'fastapi':117,752 'field':290,293,308,321,336,509 'file':583,584,637,638 'five':278,699 'five-ti':277,698 'fixtur':653 'follow':15,37 'full':268,405,499,577,602 'get':121,124,215,362,369,388,545,723 'global':217,731 'grace':141,477,608,661 'grade':9,31 'guid':579 'handl':470,473,630 'hardcod':430 'hierarchi':275 'hint':498 'http':128,633 'httpexcept':131 'id':67,264,306,331,371,374,377,391,395,548,557,566 'ident':55 'implement':27,269,520,601 'import':81,85,101,183,187,191 'initi':152 'inject':690,721 'input':814 'instal':46,49 'integr':616 'intern':342 'isol':693 'json':513 'key':74,111,157,238,393,422,429,436,453,457,622,692,741 'known':434 'layer':133,351,707 'length':295,298,324 'level':730 'limit':776 'local':96,439 'localhost':106,206 'log':632 'logic':135,475,667,710 'loop':754 'maintain':697 'map':635 'match':459,785 'max':297 'method':504 'min':294,323 'minim':755 'miss':822 'mock':527,551,614,656,726 'mock_cosmos_container.read_item.return':555 'mocker':530 'mocker.magicmock':532 'mocker.patch':533 'model':139,274,280,490,491,701 'modul':149,169,469,646,729 'module-level':728 'move':627 'name':64,256,291,318,487,559 'never':420,448 'nfrs':659 'none':197,224,322,366,380,385,399,401,481 'nosql':13,35 'oper':628 'option':317,319 'os.environ':90,109 'output':794 'overhead':758 'overview':116,775 'paramet':446 'parameter':442,687 'partial':314 'partit':392,452,456,621,625,691,740,746 'pattern':281,352,406,523,599,678,702,714 'perform':739 'permiss':815 'pip':48 'pool':675 'practic':20,42 'prefer':77 'prevent':689,750 'principl':23,45,410 'product':8,30,72 'production-grad':7,29 'project':327,341,348,373,379,390,546,550 'project_service.get':564 'projectbas':287,302,328 'projectcr':301 'projectindb':340 'projectservic':355 'projectupd':312 'public':503 'purpos':639 'py':5 'pydant':273 'pytest':612,652 'pytest.fixture':525 'pytest.mark.asyncio':541 'python':78,98,179,285,353,524 'qualiti':657 'queri':443,626,688,742 'quick':165 'rbac':414,684 'read':587 'readi':642 'ready-to-us':641 'refer':582 'references/client-setup.md':271,588 'references/error-handling.md':629 'references/partitioning.md':619 'references/service-layer.md':408,600 'references/testing.md':581,610 'reliabl':660 'request':304 'requir':127,412,516,813 'respons':130,330,467 'result':562 'result.id':572 'result.name':575 'retri':666 'return':205,265,361,384,400,402,480,536,539,549 'review':806 'router':118 'run':162,192 'safeti':816 'scan':747 'schema':704 'scope':787 'secret':681 'secur':18,40,411,679 'see':270,407,580 'self':359,372 'self._doc_to_model':403 'self._use_cosmos':383 'separ':284,733 'serial':514 'servic':14,26,36,132,350,472,479,603,648,706,718 'set':589 'settings.cosmos':229,234,237,246,254,262 'setup':170,618 'share':289 'singl':466 'singleton':150,173,598,677 'skeleton':650 'skill':763,779 'skill-azure-cosmos-db-py' 'source-sickn33' 'specif':801 'ssl':596 'starlette.concurrency':190 'start':166 'stop':807 'storag':712 'store':421 'str':203,292,307,320,332,347,375,378 'string':449 'substitut':797 'success':819 'syntax':447 'task':783 'tdd':22,44,515 'templat':636 'test':518,544,560,576,578,613,617,736,803 'testabl':719 'threadpool':164,194 'tier':279,700 'topic-agent-skills' 'topic-agentic-skills' 'topic-ai-agent-skills' 'topic-ai-agents' 'topic-ai-coding' 'topic-ai-workflows' 'topic-antigravity' 'topic-antigravity-skills' 'topic-claude-code' 'topic-claude-code-skills' 'topic-codex-cli' 'topic-codex-skills' 'transient':672 'treat':792 'type':346,497,500 'unavail':145,484,665 'unit':735 'updat':315 'url':89,105,233,245 'use':276,357,416,445,494,508,521,644,761,777 'user':123,126,460 'valid':137,454,455,802 'valu':537,556 'variabl':57 'verifi':113,240 'via':161,676,685,722 'well':433 'well-known':432 'without':737 'workflow':769 'workspac':305,376,394,568 'workspaceid':310 'wrap':749 'wrapper':160 'write':517,611 'zero':680","prices":[{"id":"35614873-85a0-4c63-b20e-f2af400d3623","listingId":"ccf3fa8e-e975-4208-94e7-1b356160c758","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"sickn33","category":"antigravity-awesome-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T21:32:16.983Z"}],"sources":[{"listingId":"ccf3fa8e-e975-4208-94e7-1b356160c758","source":"github","sourceId":"sickn33/antigravity-awesome-skills/azure-cosmos-db-py","sourceUrl":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/azure-cosmos-db-py","isPrimary":false,"firstSeenAt":"2026-04-18T21:32:16.983Z","lastSeenAt":"2026-04-24T18:50:29.757Z"}],"details":{"listingId":"ccf3fa8e-e975-4208-94e7-1b356160c758","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"sickn33","slug":"azure-cosmos-db-py","github":{"repo":"sickn33/antigravity-awesome-skills","stars":34928,"topics":["agent-skills","agentic-skills","ai-agent-skills","ai-agents","ai-coding","ai-workflows","antigravity","antigravity-skills","claude-code","claude-code-skills","codex-cli","codex-skills","cursor","cursor-skills","developer-tools","gemini-cli","gemini-skills","kiro","mcp","skill-library"],"license":"mit","html_url":"https://github.com/sickn33/antigravity-awesome-skills","pushed_at":"2026-04-24T06:41:17Z","description":"Installable GitHub library of 1,400+ agentic skills for Claude Code, Cursor, Codex CLI, Gemini CLI, Antigravity, and more. Includes installer CLI, bundles, workflows, and official/community skill collections.","skill_md_sha":"b1ad3957ed24c0f2efb1be8c412781bc2f589fa1","skill_md_path":"skills/azure-cosmos-db-py/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/azure-cosmos-db-py"},"layout":"multi","source":"github","category":"antigravity-awesome-skills","frontmatter":{"name":"azure-cosmos-db-py","description":"Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles."},"skills_sh_url":"https://skills.sh/sickn33/antigravity-awesome-skills/azure-cosmos-db-py"},"updatedAt":"2026-04-24T18:50:29.757Z"}}