Home > database >  Get all parent hierarchy from a work Item via API Azure Boards
Get all parent hierarchy from a work Item via API Azure Boards

Time:09-29

I need to get all the parent hierarchy from a work item.

The parent of the parent of the parent.. find all the parent links.

There is a way to do it via API?

Thanks :)

CodePudding user response:

Yes, you can.

But you must use code to handle this situation. The below is a Python demo.

from azure.devops.connection import Connection
from msrest.authentication import BasicAuthentication

#get all the work items linked to a work item
def get_work_items_parents(Organization_Name, personal_access_token, wi_id):
    #get a connection to Azure DevOps
    organization_url = 'https://dev.azure.com/' Organization_Name
    credentials = BasicAuthentication('', personal_access_token)
    connection = Connection(base_url=organization_url, creds=credentials)
    work_item_tracking_client = connection.clients.get_work_item_tracking_client()
    work_item = work_item_tracking_client.get_work_item(wi_id, expand="relations")
    #get the work item links
    for item in work_item.relations:
        #get parent and child work items
        if item.attributes['name'] == 'Parent':
            #get the work item id
            work_item_id = item.url.split('/')[-1]
            #get the work item
            linked_work_item = work_item_tracking_client.get_work_item(work_item_id)

            #add the work item to the list
            work_items_parents.append(linked_work_item)
            #get the parents of the parent
            get_work_items_parents(Organization_Name, personal_access_token, work_item_id)
    return work_items_parents


personal_access_token = 'xxx'
Organization_Name = 'xxx'
workitem_id = 120
#create a list
work_items_parents = []

items = get_work_items_parents(Organization_Name, personal_access_token, workitem_id)

for item in items:
    print(item.fields['System.Title'])

I can successfully get all parents of workitem id '120':

enter image description here

enter image description here

enter image description here

enter image description here

The above is the API of Python SDK Demo, if you want to use REST API, I can also give you an idea.

Just call this REST API:

https://dev.azure.com/<Organization Name>/<Project Name>/_apis/wit/workitems/<Workitem ID>?api-version=6.0&$expand=relations

You can call it again after getting the current parent:

enter image description here

Official document of the REST API:

enter image description here

  • Related