---
title: Python SDK
description: Official Python SDK for TraceRTM API integration
keywords: [python, sdk, api, client, pip, poetry]
audience: developer
difficulty: intermediate
---

import { Callout } from 'fumadocs-ui/components/callout';
import { Steps, Step } from 'fumadocs-ui/components/steps';
import { Tabs, Tab } from 'fumadocs-ui/components/tabs';

# Python SDK

The official Python SDK for TraceRTM provides a pythonic interface to the REST API.

## Installation

<Tabs items={['pip', 'poetry', 'uv']}>
  <Tab value="pip">
    ```bash
    pip install tracertm
    ```
  </Tab>

  <Tab value="poetry">
    ```bash
    poetry add tracertm
    ```
  </Tab>

  <Tab value="uv">
    ```bash
    uv pip install tracertm
    ```
  </Tab>
</Tabs>

**Requirements**:
- Python 3.8+
- Recommended: Python 3.11+ for best performance

## Quick Start

<Steps>
  <Step>
    ### Initialize client

    ```python
    from tracertm import TraceRTMClient

    # Using API key
    client = TraceRTMClient(
        api_key="your-api-key-here"
    )

    # Or using environment variable
    import os
    client = TraceRTMClient(
        api_key=os.getenv("TRACERTM_API_KEY")
    )

    # With custom base URL (self-hosted)
    client = TraceRTMClient(
        api_key="your-api-key",
        base_url="https://tracertm.yourcompany.com/api/v1"
    )
    ```

    <Callout type="tip">
    Store your API key in environment variables, never in code!
    </Callout>
  </Step>

  <Step>
    ### Create a project

    ```python
    project = client.projects.create(
        name="My Project",
        key="MYPROJ",
        description="Requirements tracking for my project"
    )

    print(f"Created project: {project.id}")
    # Output: Created project: proj-abc123
    ```
  </Step>

  <Step>
    ### Create requirements

    ```python
    # Business requirement
    br = client.requirements.create(
        project_id=project.id,
        type="BR",
        title="Increase user engagement",
        description="Platform shall increase DAU by 20%",
        priority="MUST"
    )

    # Functional requirement
    fr = client.requirements.create(
        project_id=project.id,
        type="FR",
        title="Recommendation engine",
        description="System shall provide personalized recommendations",
        priority="MUST",
        custom_fields={
            "component": "Engine",
            "sprint": 5
        }
    )

    print(f"Created: {br.id}, {fr.id}")
    ```
  </Step>

  <Step>
    ### Create traceability link

    ```python
    link = client.links.create(
        source_id=fr.id,
        target_id=br.id,
        link_type="satisfies"
    )

    print(f"Linked {fr.id} -> {br.id}")
    ```
  </Step>

  <Step>
    ### Generate traceability matrix

    ```python
    matrix = client.views.traceability_matrix(
        project_id=project.id,
        source_types=["BR"],
        target_types=["FR", "TC"]
    )

    # Print coverage
    print(f"Coverage: {matrix.coverage_percentage}%")

    # Show gaps
    for gap in matrix.gaps:
        print(f"Missing: {gap.item_id} has no {gap.missing_type}")
    ```
  </Step>
</Steps>

## Working with Projects

### List projects

```python
# List all projects
projects = client.projects.list()

for project in projects:
    print(f"{project.key}: {project.name}")

# With filters
projects = client.projects.list(
    status="active",
    sort="created_at",
    order="desc"
)
```

### Get project by ID

```python
project = client.projects.get("proj-abc123")

print(f"Project: {project.name}")
print(f"Created: {project.created_at}")
print(f"Items: {project.item_count}")
```

### Update project

```python
project = client.projects.update(
    "proj-abc123",
    description="Updated description",
    settings={
        "require_approval": True,
        "min_test_coverage": 0.90
    }
)
```

### Delete project

```python
client.projects.delete("proj-abc123")
```

<Callout type="warn">
Project deletion is **permanent** and deletes all items, links, and baselines!
</Callout>

## Working with Requirements

### Create requirement

```python
req = client.requirements.create(
    project_id="proj-abc123",
    type="FR",  # FR, BR, NFR, etc.
    title="User authentication",
    description="System shall authenticate users via email/password",
    priority="MUST",  # MUST, SHOULD, COULD, WONT
    status="draft",
    acceptance_criteria=[
        "Valid credentials create session",
        "Invalid credentials return 401",
        "Sessions expire after 24h"
    ],
    custom_fields={
        "component": "Auth",
        "complexity": "M",
        "story_points": 5
    }
)
```

### List requirements

```python
# All requirements
requirements = client.requirements.list(
    project_id="proj-abc123"
)

# With filters
requirements = client.requirements.list(
    project_id="proj-abc123",
    type="FR",
    status="approved",
    priority=["MUST", "SHOULD"],
    custom_fields={"component": "Auth"}
)

# Pagination
requirements = client.requirements.list(
    project_id="proj-abc123",
    page=2,
    per_page=50
)
```

### Search requirements

```python
# Full-text search
results = client.requirements.search(
    project_id="proj-abc123",
    query="authentication login OAuth",
    fields=["title", "description"]
)

for req in results:
    print(f"{req.id}: {req.title}")
```

### Update requirement

```python
req = client.requirements.update(
    "req-fr-123",
    status="approved",
    priority="MUST",
    custom_fields={"sprint": 6}
)
```

### Delete requirement

```python
client.requirements.delete("req-fr-123")
```

## Working with Links

### Create link

```python
link = client.links.create(
    source_id="req-fr-1",
    target_id="req-br-1",
    link_type="satisfies",  # See link types reference
    rationale="FR implements business requirement",
    strength="strong"  # strong, weak
)
```

### List links

```python
# All links for an item
links = client.links.list(item_id="req-fr-1")

# Outgoing links only
outgoing = client.links.list(
    source_id="req-fr-1"
)

# Incoming links only
incoming = client.links.list(
    target_id="req-fr-1"
)

# By link type
satisfies_links = client.links.list(
    item_id="req-fr-1",
    link_type="satisfies"
)
```

### Delete link

```python
client.links.delete(link_id="link-abc123")
```

## Bulk Operations

### Bulk create requirements

```python
requirements = client.requirements.bulk_create([
    {
        "project_id": "proj-123",
        "type": "FR",
        "title": "Requirement 1",
        "priority": "MUST"
    },
    {
        "project_id": "proj-123",
        "type": "FR",
        "title": "Requirement 2",
        "priority": "SHOULD"
    }
])

print(f"Created {len(requirements)} requirements")
```

### Bulk update

```python
updated = client.requirements.bulk_update(
    ids=["req-1", "req-2", "req-3"],
    updates={
        "status": "approved",
        "custom_fields": {"sprint": 5}
    }
)
```

### Bulk delete

```python
client.requirements.bulk_delete(
    ids=["req-1", "req-2", "req-3"]
)
```

## Baselines

### Create baseline

```python
baseline = client.baselines.create(
    project_id="proj-123",
    name="v1.0.0",
    description="Release 1.0.0",
    freeze=True,  # Make immutable
    include_types=["BR", "FR", "NFR", "TC"]
)

print(f"Baseline: {baseline.id}")
print(f"Items: {baseline.item_count}")
```

### Compare baselines

```python
diff = client.baselines.compare(
    baseline_id="baseline-v1.0.0",
    compare_to="current"  # or another baseline ID
)

print(f"Added: {len(diff.added)}")
print(f"Modified: {len(diff.modified)}")
print(f"Deleted: {len(diff.deleted)}")

for item in diff.added:
    print(f"  + {item.id}: {item.title}")
```

## Traceability Analysis

### Coverage analysis

```python
coverage = client.analysis.coverage(
    project_id="proj-123",
    source_type="FR",
    target_type="TC"
)

print(f"Coverage: {coverage.percentage}%")
print(f"Covered: {coverage.covered_count}/{coverage.total_count}")

# Items without coverage
for item in coverage.gaps:
    print(f"Missing coverage: {item.id}")
```

### Impact analysis

```python
impact = client.analysis.impact(
    item_id="req-fr-1",
    depth=3  # How many levels deep
)

print(f"Affects {len(impact.affected_items)} items:")
for item in impact.affected_items:
    print(f"  {item.type} {item.id}: {item.title}")
```

### Gap analysis

```python
gaps = client.analysis.gaps(
    project_id="proj-123"
)

print("Requirements without tests:")
for req in gaps.untested_requirements:
    print(f"  {req.id}: {req.title}")

print("\nTests without requirements:")
for test in gaps.orphaned_tests:
    print(f"  {test.id}: {test.title}")
```

## Error Handling

```python
from tracertm import TraceRTMClient
from tracertm.exceptions import (
    AuthenticationError,
    ResourceNotFoundError,
    ValidationError,
    RateLimitError
)

client = TraceRTMClient(api_key="your-key")

try:
    req = client.requirements.create(
        project_id="proj-123",
        type="INVALID_TYPE",
        title="Test"
    )
except ValidationError as e:
    print(f"Validation failed: {e.message}")
    print(f"Errors: {e.details}")
except ResourceNotFoundError as e:
    print(f"Not found: {e.resource_type} {e.resource_id}")
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
    import time
    time.sleep(e.retry_after)
    # Retry request
```

## Async Support

For high-performance applications, use the async client:

```python
import asyncio
from tracertm import AsyncTraceRTMClient

async def main():
    client = AsyncTraceRTMClient(api_key="your-key")

    # Create multiple requirements concurrently
    tasks = [
        client.requirements.create(
            project_id="proj-123",
            type="FR",
            title=f"Requirement {i}"
        )
        for i in range(10)
    ]

    requirements = await asyncio.gather(*tasks)
    print(f"Created {len(requirements)} requirements")

    await client.close()

asyncio.run(main())
```

## Configuration

### Client options

```python
from tracertm import TraceRTMClient

client = TraceRTMClient(
    api_key="your-key",
    base_url="https://api.tracertm.io/v1",
    timeout=30,  # Request timeout in seconds
    max_retries=3,  # Auto-retry failed requests
    retry_delay=1.0,  # Delay between retries
    verify_ssl=True,  # SSL verification
    user_agent="MyApp/1.0"
)
```

### Logging

```python
import logging

# Enable SDK logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger("tracertm")
logger.setLevel(logging.DEBUG)

# Now all API calls are logged
client = TraceRTMClient(api_key="your-key")
```

## Examples

### Complete workflow

```python
from tracertm import TraceRTMClient

# Initialize
client = TraceRTMClient(api_key="your-key")

# Create project
project = client.projects.create(
    name="Mobile App",
    key="MOBILE"
)

# Create business requirement
br = client.requirements.create(
    project_id=project.id,
    type="BR",
    title="User authentication",
    priority="MUST"
)

# Create functional requirements
fr_email = client.requirements.create(
    project_id=project.id,
    type="FR",
    title="Email/password login",
    priority="MUST"
)

fr_oauth = client.requirements.create(
    project_id=project.id,
    type="FR",
    title="OAuth social login",
    priority="SHOULD"
)

# Link FRs to BR
client.links.create(fr_email.id, br.id, "satisfies")
client.links.create(fr_oauth.id, br.id, "satisfies")

# Create test cases
tc1 = client.test_cases.create(
    project_id=project.id,
    title="Test email login",
    steps=["Enter email", "Enter password", "Click login"]
)

tc2 = client.test_cases.create(
    project_id=project.id,
    title="Test OAuth login",
    steps=["Click Google", "Authorize", "Redirect"]
)

# Link tests to requirements
client.links.create(tc1.id, fr_email.id, "verifies")
client.links.create(tc2.id, fr_oauth.id, "verifies")

# Check coverage
coverage = client.analysis.coverage(
    project_id=project.id,
    source_type="FR",
    target_type="TC"
)

print(f"Test coverage: {coverage.percentage}%")

# Generate matrix
matrix = client.views.traceability_matrix(
    project_id=project.id
)

# Export to Excel
matrix.export("traceability_matrix.xlsx")
```

## Next Steps

- [API Reference](/docs/api/rest-api) - Complete REST API documentation
- [Python SDK Examples](/docs/sdk/python/examples) - More code examples
- [Error Handling](/docs/sdk/python/errors) - Exception reference

<Callout type="info">
**Questions?** Check [GitHub Issues](https://github.com/tracertm/python-sdk/issues) or join [Discord #sdk-help](https://discord.gg/tracertm)
</Callout>
