How to close a JIRA ticket using the REST api

logoJIRAPNGI had to close a bunch of tickets during a cleanup operation and I thought I better spend a few hours learning something new instead of mindlessly clicking buttons into a web interface and waiting for it to refresh. So I set out to learn about JIRA’s REST api. Using python, because why not, I want to learn python as well.

Fortunately Atlassian has pretty good docs and tutorials on it’s webpages. Unfortunately our JIRA instance requires you to fill out the time spent and some custom fields when you want to transition a ticket to the “Resolved” state.

The following hackish script is the result. It will require the username and password for the JIRA instance, the ticket, the time spent and a comment as parameters. Proper argument and error handling is left as an exercise to the reader.

#!/usr/bin/python
import urllib
import urllib2
import base64
import json
import sys

if (len(sys.argv) != 6):
     print "Usage: closeticket.py JiraUser JiraPassword JiraTicket TimeSpent \"Comment text\""
     sys.exit(2)

username = sys.argv[1]
password = sys.argv[2]
key = sys.argv[3]
timespent = sys.argv[4]
comment = sys.argv[5]

# Modify the url to suit your jira instance
url = 'https://jira.url/rest/api/2/issue/%s/transitions' % key
auth = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
data = json.dumps({
  "update": {
    "assignee": [
      {
        "set": {
          "name": username
        }
      }
    ],
    "comment": [
      {
        "add": {
          "body": comment
        }
      }
    ],
    "worklog": [
      {
        "add": {
          "timeSpent": timespent
        }
      }
    ],
    "customfield_10513": [
      {
        "set": [
          {
            "id": "17102"
          }
        ]
      }
    ],
    "customfield_11612": [
      {
        "set": {
          "id": "21903",
          "child": {
            "id": "21904"
          }
        }
      }
    ]
  },
  "transition": {
    "id": "5"
  }
})

request = urllib2.Request(url, data, {
    'Authorization': 'Basic %s' % auth,
    'Content-Type': 'application/json',
})
print urllib2.urlopen(request).read()

Note: custom fields are a bitch. You can use the following to figure them out:

https://jira.url/rest/api/2/issue/MY-ISSUE/transitions?expand=transitions.fields

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.