# Advanced API Implementations

## Getting Started

Before exploring the examples, make sure to log in to the platform. More information on this can be found in the [API Beginner Guide](https://help.connected.illumina.com/emedgene/emedgene-analyze-manual/integrations/api-beginner-guide).

After authentication, you will receive a token, which remains valid for a certain period of time.

{% hint style="info" %}
For more information on advanced features, parameters, and additional examples, be sure to check out our Swagger documentation by going to `https://<hostname>.emg.illumina.com/api/apidoc/swagger#/`
{% endhint %}

## Use cases

* Automating Case Management: Creation and Status Check
* Assigning Participants
* Retrieving Case Info, Tags, Variants, and Changing Status
* Managing Finalized Cases and Generating Reports
* Creating a Custom Preset Group with Additional Gene Panels

### Automating Case Management: Creation and Status Check

This example demonstrates how to automate case management, including case creation, checking if the case status is "finalized," and generating a report.

#### Step 1: Create the Payload

First, construct a JSON payload with all the necessary case data.

{% hint style="info" %}
Refer to the API documentation for more details on required fields, or go to `https://<hostname>.emg.illumina.com/api/apidoc/swagger#/Cases/post__api_cases_v2_cases`
{% endhint %}

#### Step 2: Send a POST Request

To create a case, send a POST request using the payload. Remember to replace any values enclosed in `< >` with your specific data.

```
import requests

route_case_creation_url = 'https://<hostname>.emg.illumina.com/api/cases/v2/cases/'
payload = {
    "sharing_level": 0,
    "should_upload": False,
    "test_data": {
        "analysis_type": None,
        "boostGenes": False,
        "consanguinity": False,
        "disease_penetrance": 100,
        "disease_severity": "",
        "diseases": [],
        "gene_list": {
            "id": 1,
            "type": "all",
            "visible": False
        },
        "incidental_findings": None,
        "inheritance_modes": [],
        "labels": [],
        "notes": "",
        "patients": {
            "other": [],
            "proband": {
                "dead": False,
                "detailed_ethnicity": {
                    "maternal": [],
                    "paternal": []
                },
                "fastq_sample": "<proband sample name>",
                "gender": "<proband gender>",
                "healthy": False,
                "id": "proband",
                "ignore": False,
                "notes": "",
                "phenotypes": [
                    {
                        "id": "phenotypes/<EMG_PHENOTYPE_0011856>",
                        "name": "Pica"
                    },
                    {
                        "id": "phenotypes/<EMG_PHENOTYPE_0000969>",
                        "name": "Edema"
                    }
                ],
                "quality": "",
                "relationship": "Test Subject",
                "zygosity": ""
            }
        },
        "sample_type": "<fastq or vcf>",
        "samples": [
            {
                "directoryPath": "",
                "fastq": "<proband sample name>",
                "sampleFiles": [
                    {
                        "filename": "<proband file 1>.fastq.gz",
                        "path": "<full path/proband file 1>.fastq.gz",
                        "size": <file size>,
                        "status": "uploaded",
                        "storage_id": <storage provider id>
                    },
                    {
                        "filename": "<proband file 2>.fastq.gz",
                        "path": "<full path/proband file 2>.fastq.gz",
                        "size": <file size>,
                        "status": "uploaded",
                        "storage_id": <storage provider id>
                    }
                ],
                "sampleType": "<fastq or vcf>",
                "status": "uploaded",
                "storage_id": <storage provider id>
            }
        ],
        "selected_preset_set": None,
        "sequence_info": {
            "intersect_bed_id": None,
            "kit": "<kit name>",
            "kit_id": <kit id>
        },
        "type": "<case type>"
    }
}

headers = {'Authorization': 'Bearer <your-auth-token>'}
response = requests.post(route_case_creation_url, json=payload, headers=headers)
```

#### Step 3: Retrieve Case Status and Name

After creating the case, you can retrieve the status and name from the API response.

```
# Check response status:
status = response.json().get("Status")

# Get the case name:
case_name = response.json().get("name")
```

### Assigning Participants

#### Step 1: Retrieve Participant IDs by Email

Before assigning participants to cases, you can retrieve their IDs by searching for their email addresses.

```
import requests

# Define the email addresses you want to search for
emails_to_search = ["user1@example.com", "user2@example.com"]

participant_ids = []
user_url = 'https://<hostname>.emg.illumina.com/api/user/org_users/'
response = requests.get(user_url, headers=headers)
if response.status_code == 200:
    users = response.json().get("hits", [])
    for user in users:
        if user.get("email") in emails_to_search:
            participant_ids.append(user.get("id"))
```

#### Step 2: Assign Participants to the Case

Finally, assign participants to the case using their IDs.

```
assign_url = f'https://<hostname>.emg.illumina.com/api/participant/{case_name}'

payload = {"action": "assign", "ids": participant_ids}

response = requests.post(url=assign_url, json=payload, headers=headers)

if response.status_code == 200:
    print(f"Participants {participant_ids} assigned to case {case_name}.")
else:
    print(f"Failed to assign participants to case {case_name}. Response: {response.json()}")
```

### Retrieving Case Info, Tags, Variants, and Changing Status

This example demonstrates how to retrieve tagged variants and the associated variant information from a case, and change the case status.

#### Step 1: Obtain the Case Name

If you don't have the case name yet, follow the steps outlined in Steps 1 and 2 of [Automating Case Management: Creation](#automating-case-management-creation-status-check-and-reporting) to create a case and retrieve the case name.

#### Step 2: Retrieve case info

Use this API route to get some basic information on a case: creation time, creator, last updated time, case name, case status.

```
import requests

url = 'https://<hostname>.emg.illumina.com/api/test/{case_name}/info'
headers = {
    'Authorization': 'Bearer <your-auth-token>'
}

response = requests.get(url=url, headers=headers)

# Output the case information
print(response.json())
```

#### Step 3: Send a GET Request to Retrieve Case Tags

To pull the case data, including tagged variants, send a GET request.

```
import requests

url = 'https://<hostname>.emg.illumina.com/api/candidates/{case_name}'
headers = {
    'Authorization': 'Bearer <your-auth-token>'
}

response = requests.get(url=url, headers=headers)

# Output the variants with tags and their information
print(response.json())
```

{% hint style="info" %}
For more information, check out the Swagger documentation at `https://<hostname>.emg.illumina.com/api/apidoc/swagger#/Candidates/get__api_candidates_%7Bcase_name%7D`
{% endhint %}

#### Step 4: Update Case Status to a Custom Status

After retrieving the case, update the status to `"custom_status_1"`.

```
case_name = case.get("name")
update_url = f'https://<hostname>.emg.illumina.com/api/test/{case_name}'

payload = {"status": "custom_status_1"}

response = requests.put(url=update_url, json=payload, headers=headers)

if response.status_code == 200:
    print(f"Case {case_name} updated to 'custom_status_1'.")
else:
    print(f"Failed to update case {case_name}. Response: {response.json()}")
```

### Managing Finalized Cases and Generating Reports

#### Step 1: Retrieve Cases Finalized in the Last 24 Hours

Retrieve cases that were finalized within the last 24 hours.

```
from datetime import datetime, timedelta

# Calculate the date 24 hours ago
from_status_change_date = (datetime.now() - timedelta(days=1)).isoformat()

url = f'https://<hostname>.emg.illumina.com/api/test?from_status_change_date={from_status_change_date}&status=finalized'

response = requests.get(url=url, headers=headers)

finalized_cases = response.json()
```

Another option for retrieving a finalized case is to use [webhooks](https://help.connected.illumina.com/emedgene/emedgene-analyze-manual/integrations/webhook-integration). This option allows to receive notifications on case status change instead of checking via API.

#### Step 2: Generate a Report

Reports can only be generated for **finalized** cases. To generate a report, send the following GET request:

```
url = 'https://<hostname>.emg.illumina.com/api/test/{case_name}/reports/English/null/?candidates=true&full_export=true&incidental=true'
headers = {
    'Authorization': 'Bearer <your-auth-token>'
}
response = requests.get(url=url, headers=headers)
print(response.json())
```

{% hint style="info" %}
For more information, check out the Swagger documentation at `https://<hostname>.emg.illumina.com/api/apidoc/swagger#/Reports/get__api_test_v2_%7Bcase_name%7D_reports_%7Breport_type%7D_%7Breport_id%7D`
{% endhint %}

### Creating a Custom Preset Group with Additional Gene Panels

This example demonstrates how to create a **custom preset group** by combining an existing preset group (created with a case) and adding additional gene lists, HPO terms, inheritance modes, or other data on top of it.

#### **Step 1: Create a Case with an Existing Preset Group**

Before creating a custom preset group, ensure that a case has already been created using an existing preset group. For details on how to create a case, refer to [Automating Case Management: Creation](#automating-case-management-creation-status-check-and-reporting).

#### **Step 2: Create a Custom Preset Group**

Once the case is created, use the API to add custom gene lists on top of the existing preset group associated with the case. Here's the Python code to achieve this:

```
import requests

case_name = "EMG123456789"
url = f'https://<hostname>.emg.illumina.com/api/test/<case_name>/preset_group'

headers = {'Authorization': 'Bearer <your-api-key>'}

# Define the gene lists to be added on top of the existing preset group
first_gene_list_name = "my gene list"
first_gene_list_id = 1
second_gene_list_name = "my gene list 2"
second_gene_list_id = 2

data = {
    "name": "<name-of-new-custom-preset-group>",
    "filter": {
        "search": [
            {
                "id": first_gene_list_id,
                "name": first_gene_list_name,
                "type": "gene list",
                "value": first_gene_list_name
            },
            {
                "id": second_gene_list_id,
                "name": second_gene_list_name,
                "type": "gene list",
                "value": second_gene_list_name
            }
        ]
    }
}

response = requests.post(url, json=data, headers=headers)

if response.status_code == 201:
    print("Custom preset group created successfully.")
else:
    print(f"Failed to create custom preset group. Status code: {response.status_code}")
```

{% hint style="info" %}
For more information, check out the Swagger documentation at `https://<hostname>.emg.illumina.com/api/apidoc/swagger#/Cases/post__api_test_%7Bcase_name%7D_preset_group`
{% endhint %}
