Official agent skill

Azure Cosmos DB Py

by microsoft in microsoft/skills

Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns.

OfficialMITAuto-check passedDatabases

Install Azure Cosmos DB Py

skills CLI
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install microsoft/skills azure-cosmos-db-py --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .claude/skills/azure-cosmos-db-py && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
azure-cosmos-db-py
GitHub stars
3.1k
Token cost
~2.8k tokens
SKILL.md length
530 words
Files
9 (incl. references, assets)
Skills in repo
150
Repo updated
First seen
Licence
MIT

At a glance

Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns.

  • Works in 3 steps: Client Module Setup → Pydantic Model Hierarchy → Service Layer Pattern
  • Implementing database client setup with dual auth (DefaultAzureCredential + emulator)
  • SKILL.md covers Installation, Environment Variables, Authentication & Lifecycle and Architecture Overview, plus 6 more sections
  • Runs Python scripts from its folder; calls pip; reaches learn.microsoft.com; needs AZURE_TOKEN_CREDENTIALS and COSMOS_KEY

What it does

Azure Cosmos DB Py is an agent skill from microsoft/skills, published by the product's own GitHub organization. Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns. Use when implementing database client setup with dual auth (DefaultAzureCredential + emulator), service layer classes with CRUD operations, partition key strategies, parameterized queries, or TDD patterns for Cosmos. Triggers on phrases like "Cosmos DB", "NoSQL database", "document store", "add persistence", "database service layer", or "Python Cosmos SDK".

Its SKILL.md is about 2.8k tokens, which your agent loads only when the skill is triggered. The skill folder holds 10 other files, including reference files and assets (for example `assets/conftest_template.py`, `assets/cosmos_client_template.py` and `assets/service_template.py`).

It sits in Databases, covering NoSQL databases, Backend development and Test-driven development. It works with Azure Cosmos DB, Microsoft Azure, Python and Visual Studio Code. The repository describes itself as: Skills, MCP servers, Custom Agents, Agents.md for SDKs to ground Coding Agents. The licence is MIT.

When your agent uses it

  • Implementing database client setup with dual auth (DefaultAzureCredential + emulator)
  • Service layer classes with CRUD operations
  • Partition key strategies
  • Parameterized queries

Example prompts

  • “Cosmos DB”
  • “NoSQL database”
  • “document store”
  • “/azure-cosmos-db-py”

Requirements

  • Python 3
  • A credential in COSMOS_KEY

Workflow steps

3 steps, taken from the step headings in SKILL.md.

  1. Client Module Setup
  2. Pydantic Model Hierarchy
  3. Service Layer Pattern

What it can do on your machine

Read from SKILL.md and the folder at commit d5741a1. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • pip

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • learn.microsoft.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • AZURE_TOKEN_CREDENTIALS
    • COSMOS_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Azure Cosmos DB Py loads about 2.8k tokens when it runs, and up to ~15k if it reads all its reference files. Until then it costs about 118 tokens; SKILL.md has 530 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~118
When it runs · the whole SKILL.md, loaded when a task matches
~2.8k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~15k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from microsoft/skills at commit d5741a1, republished under its MIT licence (© microsoft). 530 words, ~2,759 tokens.

Download SKILL.mdSave it as .claude/skills/azure-cosmos-db-py/SKILL.md (or your agent's skills folder). This skill also uses 8 other files; get the full folder from GitHub.
name
azure-cosmos-db-py
description
Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns. Use when implementing database client setup with dual auth (DefaultAzureCredential + emulator), service layer classes with CRUD operations, partition key strategies, parameterized queries, or TDD patterns for Cosmos. Triggers on phrases like "Cosmos DB", "NoSQL database", "document store", "add persistence", "database service layer", or "Python Cosmos SDK".
license
MIT
metadata.author
Microsoft
metadata.version
1.0.0
metadata.package
azure-cosmos

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/  # 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 production

Authentication & Lifecycle

🔑 Two rules apply to every code sample below:

  1. 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: DefaultAzureCredential works as-is.
    • Production: set AZURE_TOKEN_CREDENTIALS=prod (or AZURE_TOKEN_CREDENTIALS=<specific_credential>) to constrain the credential chain to production-safe credentials.
  2. 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: and async with DefaultAzureCredential() as credential: (from azure.identity.aio)

Snippets may abbreviate this setup, but production code should always follow both rules.

DefaultAzureCredential (preferred):

python
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):

python
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:

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:
        # 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_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

Show full SKILL.md (242 more words)Show less

Best Practices

  1. Pick sync OR async and stay consistent. Do not mix azure.xxx sync clients with azure.xxx.aio async clients in the same call path. Choose one mode per module.
  2. 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 async DefaultAzureCredential from azure.identity.aio, also use async with credential: so tokens and transports are cleaned up.

Reference Files

FileWhen to Read
references/client-setup.mdSetting up Cosmos client with dual auth, SSL config, singleton pattern
references/service-layer.mdImplementing full service class with CRUD, conversions, graceful degradation
references/testing.mdWriting pytest tests, mocking Cosmos, integration test setup
references/partitioning.mdChoosing partition keys, cross-partition queries, move operations
references/error-handling.mdHandling CosmosResourceNotFoundError, logging, HTTP error mapping

Template Files

FilePurpose
assets/cosmos_client_template.pyReady-to-use client module
assets/service_template.pyService class skeleton
assets/conftest_template.pypytest 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

© microsoft, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 8 other files (references, assets) in .github/plugins/azure-sdk-python/skills/azure-cosmos-db-py of microsoft/skills.

  • SKILL.md
  • assets/conftest_template.py
  • assets/cosmos_client_template.py
  • assets/service_template.py
  • references/client-setup.md
  • references/error-handling.md
  • references/partitioning.md
  • references/service-layer.md
  • references/testing.md

Open the folder on GitHubat commit d5741a1

Compare with similar skills

Azure Cosmos DB Py next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Azure Cosmos DB Py compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Azure Cosmos DB Py this skillmicrosoft/skills3.1k—~2.8kAutomated safety check: PassMIT
Cosmosdb Best Practicesmicrosoft/vscode-cosmosdb200—~4.3kAutomated safety check: PassMIT
Azure Data Tables Pyaiskillstore/marketplace4334 repos~1.5kAutomated safety check: PassNone
Engineering PrinciplesAzure/agent-app-orchestrator103—~282Automated safety check: PassMIT
Fastapi Init Skilljiushiwon/wg-skills114—~1.8kAutomated safety check: NotesApache-2.0
Python Appservice Deploymicrosoft/GitHub-Copilot-for-Azure2551 repos~688Automated safety check: PassMIT

Similar skills

  • Cosmosdb Best Practices

    microsoft/vscode-cosmosdb

    Official

    Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, and SDK usage.

    200 GitHub stars~4.3k tokensUpdated today
    DatabasesAuto-check passed
  • Azure Data Tables Py

    aiskillstore/marketplace

    Azure Tables SDK for Python (Storage and Cosmos DB). An agent skill from aiskillstore/marketplace.

    433 GitHub starsUsed in 4 repos~1.5k tokens
    DatabasesAuto-check passed
  • Engineering Principles

    Azure/agent-app-orchestrator

    Official

    Agent Landing Zone Orchestrator architecture and implementation principles.

    103 GitHub stars~282 tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Fastapi Init Skill

    jiushiwon/wg-skills

    FastAPI 项目一键初始化技能。面向零基础小白,提供环境探测、自动安装、完整 Web 骨架生成、SSE 流式框架、JWT 鉴权、统一响应封装、文件上传接口、一键启动/重启脚本、Swagger 文档,内置 MySQL(默认)/ PostgreSQL / MongoDB 数据库选择。用户只需说"帮我搭一个 FastAPI 项目"即可一条命令完成从零到跑的完整链路。触发词:"FastAPI…

    114 GitHub stars~1.8k tokensUpdated 3 days ago
    Backend & APIsAuto-check: notes
  • Python Appservice Deploy

    microsoft/GitHub-Copilot-for-Azure

    Official

    Deploy Python (Flask/Django/FastAPI) code to Azure App Service Linux.

    255 GitHub starsUsed in 1 repo~688 tokens
    Backend & APIsAuto-check passed
  • Azure Storage

    microsoft/GitHub-Copilot-for-Azure

    Official

    Azure Storage Services including Blob Storage, File Shares, Queue Storage, Table Storage, and Data Lake.

    255 GitHub starsUsed in 2 repos~1.3k tokens
    DatabasesAuto-check passed

More from microsoft/skills

All 150 skills in this repo
  • Official

    Covers producer, consumer, and checkpoint-store setup for Azure Event Hubs streaming in Python, with Entra ID auth and partition targeting.

    3.1k GitHub starsUsed in 1 repo~2.3k tokens
    Auto-check passed
  • Official

    Builds podcast-style audio narration from text with Azure OpenAI's GPT Realtime Mini over WebSocket, from a Python FastAPI backend to a React player.

    3.1k GitHub starsUsed in 1 repo~947 tokens
    Auto-check passed
  • Frontend UI Dark TS

    microsoft/skills

    Official

    Build dark-themed React applications using Tailwind CSS with custom theming, glassmorphism effects, and Framer Motion animations.

    3.1k GitHub starsUsed in 5 repos~3.6k tokens
    Auto-check passed
  • Pydantic Models Py

    microsoft/skills

    Official

    Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants.

    3.1k GitHub starsUsed in 5 repos~496 tokens
    Auto-check passed
  • Official

    Reference for building on Microsoft Foundry with the azure-ai-projects Python SDK: project clients, versioned agents, evaluations, connections, datasets and indexes.

    3.1k GitHub stars~2.8k tokensUpdated today
    Auto-check passed
  • Skill Creator

    microsoft/skills

    Official

    Guide for creating effective skills for AI coding agents working with Azure SDKs and Microsoft Foundry services.

    3.1k GitHub starsUsed in 5 repos~17k tokens
    Auto-check passed

Questions about Azure Cosmos DB Py

What does Azure Cosmos DB Py do?

Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns. Azure Cosmos DB Py is an agent skill from microsoft/skills, published by the product's own GitHub organization. Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns.

When should I use Azure Cosmos DB Py?

Azure Cosmos DB Py fits situations like: implementing database client setup with dual auth (DefaultAzureCredential + emulator); service layer classes with CRUD operations; partition key strategies; parameterized queries.

How do I install Azure Cosmos DB Py in Claude Code?

Run `npx skills add microsoft/skills --skill azure-cosmos-db-py -a claude-code`. Or copy the skill folder (.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py in microsoft/skills) into .claude/skills/azure-cosmos-db-py in your project. Claude Code loads it when a task matches its description.

How do I install Azure Cosmos DB Py in Codex?

Run `npx skills add microsoft/skills --skill azure-cosmos-db-py -a codex`. Or copy the skill folder (.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py in microsoft/skills) into .agents/skills/azure-cosmos-db-py in your project. Codex loads it when a task matches its description.

Can I use Azure Cosmos DB Py in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add microsoft/skills --skill azure-cosmos-db-py -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/azure-cosmos-db-py, .gemini/skills/azure-cosmos-db-py, .github/skills/azure-cosmos-db-py and .opencode/skills/azure-cosmos-db-py in your project.

What does Azure Cosmos DB Py need to run?

Going by SKILL.md and its folder, Azure Cosmos DB Py needs Python for the scripts in its folder, the command-line tools its instructions call (pip) and credentials named AZURE_TOKEN_CREDENTIALS and COSMOS_KEY. Our summary lists: Python 3; A credential in COSMOS_KEY.

Does Azure Cosmos DB Py access the network?

SKILL.md names 1 domain. In commands or code: learn.microsoft.com; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Azure Cosmos DB Py safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Azure Cosmos DB Py use?

Azure Cosmos DB Py is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Azure Cosmos DB Py use?

About 2.8k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 12k tokens, read only when the agent opens those files.

What are the alternatives to Azure Cosmos DB Py?

Skills that share tags, products or a category with Azure Cosmos DB Py: Cosmosdb Best Practices (microsoft/vscode-cosmosdb, 200 stars), Azure Data Tables Py (aiskillstore/marketplace, 433 stars), Engineering Principles (Azure/agent-app-orchestrator, 103 stars) and Fastapi Init Skill (jiushiwon/wg-skills, 114 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Azure Cosmos DB Py?

microsoft (a GitHub organization, an official publisher) maintains it in microsoft/skills, which has 3,097 GitHub stars. The repository holds 150 skills in this directory. The repository was last updated on October 9, 2026.

Source: microsoft/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.