How to add a subtask (child issue) to an existing issue through Jira's REST API?

Hello!

I’m trying to add a subtask to an existing issue on my development environment. But I’m not succeeding on it. My app is a forge app using Jira’s REST API.

Take a look at my create subtasks function:

const foundIdTask = (data) => {
    for (let i = 0; i < data.length; i++) {
      if (data[i].untranslatedName === "Task") {
        return data[i].id;
      }
    }
    return null;
  };

  const getID = async (projectId) => {
    const res = await requestJira(
      `/rest/api/3/issuetype/project?projectId=${projectId}`
    );
    const data = await res.json();
    const taskId = foundIdTask(data);
    return taskId;
  };

const createSubtasks = async () => {
    const parentIssueKey = context.extension.issue.key;  
    const projectId = context.extension.project.id;  
    const projectKey = context.extension.project.key;
    const issueType = await getID(projectId);  

    if (!issueType) {
      console.error("No valid subtask issue type found.");
      return;
    }
 
    const requestBody = {
      "fields": {
        "project": {
          "key": projectKey
        },
        "parent": {
          "key": parentIssueKey  
        },
        "summary": "Subtask Example",
        "description": {
          "type": "doc",
          "version": 1,
          "content": [{
            "type": "paragraph",
            "content": [{
              "text": "This is a detailed description of the subtask.",
              "type": "text"
            }]
          }]
        },
        "issuetype": {
          "id": issueType  
        }
      }
    };
 
    const response = await requestJira("/rest/api/3/issue", {  
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(requestBody)
    });
 
    if (response.status === 201) {
      console.log("Subtask created successfully!");
    } else {
      console.error("Failed to create subtask:", await response.text());
    }
  };

And I’m getting this error message: Failed to create subtask: {“errorMessages”:[],“errors”:{“parentId”:“Given parent issue does not belong to appropriate hierarchy.”}}

And I don’t know what else to do because I’m getting the actual key and id of the issue that I want to work on. And I can add subtasks to this issue with no problem by using the Jira software.

Would it be my request body that is wrong? Or the route that I’m using? Or both?

Can someone help me?

Thanks!

Hi,
you should modify your subtask search function as follow:

const findFirstSubtaskIssueTypeId = (data) => data.find(issueTypeItem => issueTypeItem.subtask)?.id;