I’m working on a Java project that uses the Jira REST API. Right now I can update some fields in a Jira ticket but I’m stuck on adding labels. My current code replaces all existing labels instead of adding a new one. Here’s what I’ve got:
void modifyTicket(String ticketId) {
TicketModification changes = new TicketModificationBuilder()
.updateParentLink(PARENT_FEATURE, PARENT_VALUE)
.setReleaseVersion(makeNewVersion())
.updateField(TicketFieldId.LABELS.id,
Arrays.asList("FRESH_TAG"))
.create();
JiraApiConnection conn = JiraConnector.getConnection();
conn.getTicketHandler()
.modifyTicket(ticketId, changes)
.waitForResponse();
}
How can I add just one new label without wiping out the existing ones? Is there a way to do this without first fetching all current labels? Any help would be great!
I’ve encountered a similar issue in my work with the Jira REST API. The solution lies in using the FieldUpdateOperation.ADD operation, as mentioned. However, it’s worth noting that this approach might not be ideal in all scenarios, particularly if you’re dealing with a high volume of tickets or have performance concerns.
An alternative method I’ve found effective is to first retrieve the existing labels, then append the new one, and finally update the ticket with the combined list. This approach gives you more control and allows for additional logic if needed. Here’s a general outline:
List<String> currentLabels = getExistingLabels(ticketId);
currentLabels.add("FRESH_TAG");
updateTicketLabels(ticketId, currentLabels);
This method is slightly more verbose but offers greater flexibility and reliability in my experience.
As someone who’s worked extensively with Jira’s REST API, I can offer a bit of insight here. While the ADD operation works, I’ve found it can sometimes be unreliable, especially with older Jira versions. A robust approach I’ve used is to fetch the current labels first, then update them. Here’s a snippet that’s served me well:
JiraTicket ticket = conn.getTicketHandler().getTicket(ticketId);
List<String> currentLabels = ticket.getLabels();
currentLabels.add("FRESH_TAG");
TicketModification changes = new TicketModificationBuilder()
.updateField(TicketFieldId.LABELS.id, currentLabels)
.create();
conn.getTicketHandler().modifyTicket(ticketId, changes).waitForResponse();
This method ensures you’re always working with the most up-to-date label set, avoiding any potential conflicts or data loss. It’s a bit more code, but it’s bulletproof in my experience.
hey surfingwave, i’ve dealt with this before. try using the .add() method instead of directly setting the field. something like:
.updateField(TicketFieldId.LABELS.id, Collections.singletonList(“FRESH_TAG”), FieldUpdateOperation.ADD)
this should append your new label without touching existing ones. hope it helps!