---
title: "Examples Overview"
description: "Overview of Python SDK examples and common use cases"
---

# Examples Overview

Explore practical examples demonstrating how to use the TraceRTM Python SDK for common traceability management scenarios.

## Example Categories

### Basic Examples

Foundational patterns for getting started:

- [Basic Examples](/docs/api-reference/sdks/python/basic-examples) - CRUD operations, listing, and filtering

### Advanced Examples

Complex workflows and integrations:

- [Advanced Examples](/docs/api-reference/sdks/python/advanced-examples) - Bulk operations, async patterns, CI/CD integration

---

## Quick Reference

### Project Management

```python
from tracertm import TraceRTMClient

client = TraceRTMClient()

# Create project
project = client.projects.create(
    name="My Project",
    key="MYPROJ",
    description="Project description"
)

# List projects
for project in client.projects.iterate():
    print(f"{project.name} ({project.key})")
```

### Requirements Management

```python
# Create requirement
requirement = client.items.create(
    project_id="proj_abc123",
    type="requirement",
    title="User Authentication",
    description="Users must authenticate before accessing the system",
    priority="high",
    tags=["security"]
)

# List requirements
requirements = client.items.list(
    project_id="proj_abc123",
    type="requirement",
    status="approved"
)
```

### Test Case Management

```python
# Create test case
test_case = client.items.create(
    project_id="proj_abc123",
    type="test_case",
    title="Verify Login Success",
    fields={
        "preconditions": "User account exists",
        "steps": [
            "Navigate to login page",
            "Enter valid credentials",
            "Click login button"
        ],
        "expected_result": "User logged in successfully"
    }
)
```

### Traceability Links

```python
# Create link
link = client.links.create(
    source_id="item_req_001",
    target_id="item_tc_001",
    type="verified_by"
)

# Get item with links
item = client.items.get("item_req_001", include=["links"])
print(f"Linked items: {len(item.links)}")
```

### Search

```python
# Full-text search
results = client.search.items(
    query="authentication",
    project_ids=["proj_abc123"],
    types=["requirement", "test_case"]
)

for hit in results.items:
    print(f"{hit.item.title} (score: {hit.score})")
```

### Reports

```python
# Generate traceability matrix
matrix = client.reports.traceability_matrix(
    project_id="proj_abc123",
    source_type="requirement",
    target_type="test_case"
)

print(f"Coverage: {matrix.summary.coverage_percent}%")
print(f"Uncovered: {matrix.summary.uncovered_sources}")
```

### Bulk Operations

```python
# Bulk create
results = client.items.bulk_create([
    {"project_id": "proj_abc", "type": "requirement", "title": "Req 1"},
    {"project_id": "proj_abc", "type": "requirement", "title": "Req 2"},
    {"project_id": "proj_abc", "type": "requirement", "title": "Req 3"}
])

# Bulk update
results = client.items.bulk_update([
    {"id": "item_1", "status": "approved"},
    {"id": "item_2", "status": "approved"}
])
```

---

## Async Examples

```python
import asyncio
from tracertm import AsyncTraceRTMClient

async def main():
    async with AsyncTraceRTMClient() as client:
        # Parallel requests
        projects, items = await asyncio.gather(
            client.projects.list(),
            client.items.list(project_id="proj_abc123")
        )

        print(f"Projects: {len(projects.data)}")
        print(f"Items: {len(items.data)}")

asyncio.run(main())
```

---

## CI/CD Integration

```python
#!/usr/bin/env python3
"""CI/CD script for TraceRTM verification."""

from tracertm import TraceRTMClient
import sys

def verify_coverage(project_id: str, min_coverage: float = 80.0) -> bool:
    client = TraceRTMClient()

    coverage = client.reports.coverage(
        project_id=project_id,
        source_type="requirement",
        target_type="test_case"
    )

    print(f"Coverage: {coverage.coverage_percent:.1f}%")
    print(f"Covered: {coverage.covered_count}")
    print(f"Uncovered: {coverage.uncovered_count}")

    if coverage.uncovered_items:
        print("\nUncovered requirements:")
        for item in coverage.uncovered_items[:10]:
            print(f"  - {item.title}")

    return coverage.coverage_percent >= min_coverage

if __name__ == "__main__":
    project_id = sys.argv[1] if len(sys.argv) > 1 else "proj_abc123"

    if not verify_coverage(project_id):
        print("\nCoverage check FAILED")
        sys.exit(1)

    print("\nCoverage check PASSED")
```

---

## Error Handling

```python
from tracertm import TraceRTMClient
from tracertm.exceptions import (
    NotFoundError,
    ValidationError,
    RateLimitError,
    TraceRTMError
)
import time

client = TraceRTMClient()

def safe_get_item(item_id: str):
    try:
        return client.items.get(item_id)
    except NotFoundError:
        print(f"Item {item_id} not found")
        return None
    except RateLimitError as e:
        print(f"Rate limited, waiting {e.retry_after}s")
        time.sleep(e.retry_after)
        return safe_get_item(item_id)
    except ValidationError as e:
        print(f"Validation error: {e.errors}")
        raise
    except TraceRTMError as e:
        print(f"API error: {e.code} - {e.message}")
        raise
```

---

## Related Documentation

- [Basic Examples](/docs/api-reference/sdks/python/basic-examples) - Getting started examples
- [Advanced Examples](/docs/api-reference/sdks/python/advanced-examples) - Complex patterns
- [API Reference](/docs/api-reference/sdks/python/api-reference) - Full API documentation
- [Async Client](/docs/api-reference/sdks/python/async) - Async operations
