Cosmosdb Best Practices
microsoft/vscode-cosmosdb
Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, and SDK usage.
Build Azure Cosmos DB NoSQL services with Python/FastAPI following production-grade patterns.
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install microsoft/skills azure-cosmos-db-py --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ 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-srcUse ~/.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/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .claude/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-pyType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install microsoft/skills azure-cosmos-db-py --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .agents/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .agents/skills/azure-cosmos-db-py && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .agents/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install microsoft/skills azure-cosmos-db-py --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .cursor/skills/azure-cosmos-db-py && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .cursor/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/microsoft/skills.git --path .github/plugins/azure-sdk-python/skills/azure-cosmos-db-py--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install microsoft/skills azure-cosmos-db-py --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .gemini/skills/azure-cosmos-db-py && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .gemini/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install microsoft/skills azure-cosmos-db-pyInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .github/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .github/skills/azure-cosmos-db-py && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .github/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add microsoft/skills --skill azure-cosmos-db-py -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install microsoft/skills azure-cosmos-db-py --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/microsoft/skills.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py .opencode/skills/azure-cosmos-db-py && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "azure-cosmos-db-py" agent skill from https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-cosmos-db-py into .opencode/skills/azure-cosmos-db-py/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "azure-cosmos-db-py", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
azure-cosmos-db-pyBuild 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. 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.
3 steps, taken from the step headings in SKILL.md.
Read from SKILL.md and the folder at commit d5741a1. It shows what the files ask for, not the result of running them.
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.
Ships script files (Python), which the agent can run.
Shell commands in SKILL.md call:
pipFrom the folder's file list and the shell code blocks in SKILL.md.
Hosts in commands or code, which the agent is likely to contact:
learn.microsoft.comFrom URLs in SKILL.md, links to its own repository left out.
Names these keys or tokens, usually read from environment variables:
AZURE_TOKEN_CREDENTIALSCOSMOS_KEYFrom names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
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.
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.
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.
The full file from microsoft/skills at commit d5741a1, republished under its MIT licence (© microsoft). 530 words, ~2,759 tokens.
.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.Build production-grade Azure Cosmos DB NoSQL services following clean code, security best practices, and TDD principles.
pip install azure-cosmos azure-identityCOSMOS_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🔑 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)
...┌─────────────────────────────────────────────────────────────────┐
│ 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:
# 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
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"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
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:
@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
azure.xxx sync clients with azure.xxx.aio async clients in the same call path. Choose one mode per module.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.| 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()© microsoft, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
SKILL.md and 8 other files (references, assets) in .github/plugins/azure-sdk-python/skills/azure-cosmos-db-py of microsoft/skills.
Open the folder on GitHubat commit d5741a1
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.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Azure Cosmos DB Py this skillmicrosoft/skills | 3.1k | — | ~2.8k | Automated safety check: Pass | MIT | |
| Cosmosdb Best Practicesmicrosoft/vscode-cosmosdb | 200 | — | ~4.3k | Automated safety check: Pass | MIT | |
| Azure Data Tables Pyaiskillstore/marketplace | 433 | 4 repos | ~1.5k | Automated safety check: Pass | None | |
| Engineering PrinciplesAzure/agent-app-orchestrator | 103 | — | ~282 | Automated safety check: Pass | MIT | |
| Fastapi Init Skilljiushiwon/wg-skills | 114 | — | ~1.8k | Automated safety check: Notes | Apache-2.0 | |
| Python Appservice Deploymicrosoft/GitHub-Copilot-for-Azure | 255 | 1 repos | ~688 | Automated safety check: Pass | MIT |
microsoft/vscode-cosmosdb
Azure Cosmos DB performance optimization and best practices guidelines for NoSQL, partitioning, queries, and SDK usage.
aiskillstore/marketplace
Azure Tables SDK for Python (Storage and Cosmos DB). An agent skill from aiskillstore/marketplace.
Azure/agent-app-orchestrator
Agent Landing Zone Orchestrator architecture and implementation principles.
jiushiwon/wg-skills
FastAPI 项目一键初始化技能。面向零基础小白,提供环境探测、自动安装、完整 Web 骨架生成、SSE 流式框架、JWT 鉴权、统一响应封装、文件上传接口、一键启动/重启脚本、Swagger 文档,内置 MySQL(默认)/ PostgreSQL / MongoDB 数据库选择。用户只需说"帮我搭一个 FastAPI 项目"即可一条命令完成从零到跑的完整链路。触发词:"FastAPI…
microsoft/GitHub-Copilot-for-Azure
Deploy Python (Flask/Django/FastAPI) code to Azure App Service Linux.
microsoft/GitHub-Copilot-for-Azure
Azure Storage Services including Blob Storage, File Shares, Queue Storage, Table Storage, and Data Lake.
microsoft/skills
Covers producer, consumer, and checkpoint-store setup for Azure Event Hubs streaming in Python, with Entra ID auth and partition targeting.
microsoft/skills
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.
microsoft/skills
Build dark-themed React applications using Tailwind CSS with custom theming, glassmorphism effects, and Framer Motion animations.
microsoft/skills
Create Pydantic models following the multi-model pattern with Base, Create, Update, Response, and InDB variants.
microsoft/skills
Reference for building on Microsoft Foundry with the azure-ai-projects Python SDK: project clients, versioned agents, evaluations, connections, datasets and indexes.
microsoft/skills
Guide for creating effective skills for AI coding agents working with Azure SDKs and Microsoft Foundry services.
Categories
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.