TestRail API: Automate Test Management With CI/CD Integration

TestRail API: Automate Test Management With CI/CD Integration

TestRail's API lets you push automation results directly from your CI/CD pipeline, keeping your test management data in sync without manual updates. QA teams that automate this integration spend less time on administrative work and get real-time visibility into which automated tests are passing.

This guide covers the TestRail REST API with working examples for Python, GitHub Actions, and Robot Framework.

TestRail API Basics

TestRail's REST API is available at https://your-instance.testrail.io/index.php?/api/v2/. Authentication uses HTTP Basic Auth with your TestRail email and an API key (not your password).

Generate an API key:

  1. My Settings > API Keys > Add Key
  2. Copy the key — it won't be shown again

Base request structure:

curl -u "user@example.com:your-api-key" \
     -H "Content-Type: application/json" \
     "https://yourcompany.testrail.io/index.php?/api/v2/get_projects"

Python client setup:

pip install trcli  # Official TestRail CLI tool
# or
pip install testrail  # Third-party client

Using requests directly:

import requests
import base64

class TestRailAPI:
    def __init__(self, base_url, user, api_key):
        self.base_url = f"{base_url}/index.php?/api/v2"
        credentials = base64.b64encode(f"{user}:{api_key}".encode()).decode()
        self.headers = {
            "Authorization": f"Basic {credentials}",
            "Content-Type": "application/json"
        }
    
    def get(self, endpoint):
        response = requests.get(f"{self.base_url}/{endpoint}", headers=self.headers)
        response.raise_for_status()
        return response.json()
    
    def post(self, endpoint, data):
        response = requests.post(
            f"{self.base_url}/{endpoint}",
            headers=self.headers,
            json=data
        )
        response.raise_for_status()
        return response.json()

api = TestRailAPI(
    "https://yourcompany.testrail.io",
    "ci@example.com",
    "your-api-key"
)

Core API Operations

Get Projects and Suites

# List all projects
projects = api.get("get_projects")

# Get test suites for a project
suites = api.get(f"get_suites/PROJECT_ID")

# Get test cases in a suite
cases = api.get(f"get_cases/PROJECT_ID&suite_id=SUITE_ID")

Create a Test Run

# Create a test run from a test suite
run = api.post("add_run/PROJECT_ID", {
    "suite_id": 123,
    "name": f"Automated Regression - {datetime.now().strftime('%Y-%m-%d %H:%M')}",
    "description": "CI/CD automated run triggered by GitHub Actions",
    "include_all": True,  # Include all test cases in the suite
    "milestone_id": None,
    "assignedto_id": None
})

run_id = run["id"]
print(f"Created test run: {run_id}")

Or include specific test cases only:

run = api.post("add_run/PROJECT_ID", {
    "suite_id": 123,
    "name": "Smoke Tests",
    "include_all": False,
    "case_ids": [1001, 1002, 1003, 1004, 1005]  # Specific test case IDs
})

Add Test Results

# Status IDs: 1=Passed, 2=Blocked, 3=Untested, 4=Retest, 5=Failed
def add_result(run_id, case_id, status, elapsed=None, comment=None):
    return api.post(f"add_result_for_case/{run_id}/{case_id}", {
        "status_id": status,
        "elapsed": elapsed,   # e.g., "1m 30s"
        "comment": comment
    })

# Pass
add_result(run_id, 1001, status=1, elapsed="0m 45s", comment="Automated pass")

# Fail with details
add_result(run_id, 1002, status=5, 
           elapsed="0m 12s",
           comment="FAIL: Expected dashboard URL, got /error. Exception: TimeoutError")

Bulk Result Upload

For large test suites, batch results in a single API call:

results = [
    {"case_id": 1001, "status_id": 1, "elapsed": "0m 45s"},
    {"case_id": 1002, "status_id": 5, "elapsed": "0m 12s", 
     "comment": "Failed: selector not found"},
    {"case_id": 1003, "status_id": 1, "elapsed": "1m 20s"},
]

api.post(f"add_results_for_cases/{run_id}", {"results": results})

Close a Test Run

After all results are submitted, close the run:

api.post(f"close_run/{run_id}", {})

Closed runs are archived and their results appear in TestRail's milestone and plan reports.

pytest Integration

Automatically push pytest results to TestRail:

# conftest.py
import pytest
from datetime import datetime

class TestRailReporter:
    def __init__(self, api, run_id):
        self.api = api
        self.run_id = run_id
        self.results = []
    
    def add_result(self, case_id, status, elapsed, comment=""):
        self.results.append({
            "case_id": case_id,
            "status_id": status,
            "elapsed": elapsed,
            "comment": comment
        })
    
    def flush(self):
        if self.results:
            self.api.post(f"add_results_for_cases/{self.run_id}", 
                         {"results": self.results})
            self.api.post(f"close_run/{self.run_id}", {})

@pytest.fixture(scope="session")
def testrail_run(request):
    if not request.config.getoption("--testrail", default=False):
        return None
    
    api = TestRailAPI(
        os.environ["TESTRAIL_URL"],
        os.environ["TESTRAIL_USER"],
        os.environ["TESTRAIL_KEY"]
    )
    run = api.post(f"add_run/{os.environ['TESTRAIL_PROJECT_ID']}", {
        "suite_id": int(os.environ["TESTRAIL_SUITE_ID"]),
        "name": f"Automated - {datetime.now().strftime('%Y-%m-%d %H:%M')}",
        "include_all": True
    })
    reporter = TestRailReporter(api, run["id"])
    yield reporter
    reporter.flush()

# In your test files, use the testrail_run fixture:
def test_login(testrail_run):
    start = time.time()
    # ... test logic ...
    elapsed = f"{int(time.time() - start)}s"
    if testrail_run:
        testrail_run.add_result(case_id=1001, status=1, elapsed=elapsed)

Or use the official trcli tool which parses JUnit XML output automatically:

# Run pytest, generate JUnit XML
pytest tests/ --junitxml=results.xml

# Push to TestRail
trcli -y -h https://yourcompany.testrail.io \
      --username ci@example.com \
      --key $TESTRAIL_KEY \
      parse_junit \
      --project-id 1 \
      --title "Automated - $(date +%Y-%m-%d)" \
      -f results.xml

trcli maps test function names to TestRail test case titles automatically.

Robot Framework Integration

*** Settings ***
Library    TestRailLibrary
    ...    url=https://yourcompany.testrail.io
    ...    username=ci@example.com
    ...    password=%{TESTRAIL_KEY}
    ...    run_id=%{TESTRAIL_RUN_ID}

*** Test Cases ***
C1001 Login Test
    [Tags]    testrail=1001
    Go To    https://app.example.com/login
    Fill Text    [name="email"]    test@example.com
    # ... test steps ...

The library reads the testrail= tag and maps results to the corresponding TestRail case ID.

GitHub Actions Integration

Full workflow that creates a TestRail run, executes tests, and pushes results:

name: Automated Tests → TestRail

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v4
      
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: pip install pytest trcli
      
      - name: Run tests
        run: pytest tests/ --junitxml=results/junit.xml
        continue-on-error: true  # Push results even if tests fail
      
      - name: Push results to TestRail
        env:
          TESTRAIL_URL: ${{ vars.TESTRAIL_URL }}
          TESTRAIL_USER: ${{ vars.TESTRAIL_USER }}
          TESTRAIL_KEY: ${{ secrets.TESTRAIL_KEY }}
        run: |
          trcli -y -h $TESTRAIL_URL \
                --username $TESTRAIL_USER \
                --key $TESTRAIL_KEY \
                parse_junit \
                --project-id ${{ vars.TESTRAIL_PROJECT_ID }} \
                --title "CI - ${{ github.sha }}" \
                --run-description "Branch: ${{ github.ref_name }}" \
                -f results/junit.xml

Creating Test Cases Via API

You can create test cases programmatically — useful for syncing test cases from code comments or generating cases from test function metadata:

case = api.post(f"add_case/SECTION_ID", {
    "title": "Login with valid credentials",
    "type_id": 1,          # 1=Other, 2=Acceptance, 3=Accessibility, etc.
    "priority_id": 2,      # 1=Low, 2=Medium, 3=High, 4=Critical
    "estimate": "3m",
    "refs": "REQ-001",     # Reference IDs
    "custom_steps": [      # Custom field — steps in list format
        {
            "content": "Navigate to /login",
            "expected": "Login form displays"
        },
        {
            "content": "Enter valid credentials",
            "expected": "Fields accept input"
        }
    ]
})

Getting Test Results for Reporting

Pull results for external reporting or alerting:

# Get all results for a run
results = api.get(f"get_results_for_run/{run_id}")

# Filter failed tests
failed = [r for r in results["results"] if r["status_id"] == 5]
print(f"Failed tests: {len(failed)}")

# Get results for a specific test case across all runs
case_history = api.get(f"get_results_for_case/{run_id}/{case_id}")

Summary

The TestRail API makes test management automation straightforward: create runs, push results, close runs. The trcli tool handles the most common case (JUnit XML → TestRail) with minimal setup. For custom workflows — mapping test IDs dynamically, building bespoke reporters, syncing test cases from code — the REST API is well-documented and reliable.

The teams that get the most value from TestRail are the ones where automation results flow into TestRail automatically on every CI run, keeping the test management tool as the live source of truth rather than a manually-updated system that's always a few days stale.

Read more

Start now free