Skip to main content

Get/Access JIRA/JIRA API data using python

 Below is the program which will guide you on how to access the JIRA API data using python. First, you need to create a token for JIRA. You need to install the following libraries using the following commands:

pip install requests

pip install json-excel-converter

And the code is:

# Import the required libraries

import requests

from requests.auth import HTTPBasicAuth

import json

import pandas as pd

from json_excel_converter import Converter

from json_excel_converter.xlsx import Writer


# URL to Search all issues.

url = "YOUR JIRA URL"


# Create an authentication object,using

# registered emailID, and, token received.

auth = HTTPBasicAuth("email-d",

                     "jira token created")


# The Header parameter, should mention, the

# desired format of data.

headers = {

    "Accept": "application/json"

}

# Mention the JQL query.

# Here, all issues, of a project, are

# fetched,as,no criteria is mentioned.

query = {

    'jql': 'JIRA PROJECT NAME'

}


# Create a request object with above parameters.

response = requests.request(

    "GET",

    url,

    headers=headers,

    auth=auth,

    params=query

)


# Get all project issues,by using the

# json loads method.

projectIssues = json.dumps(json.loads(response.text),

                           sort_keys=True,

                           indent=4,

                           separators=(",", ": "))


# The JSON response received, using

# the requests object,

# is an intricate nested object.

# Convert the output to a dictionary object.

dictProjectIssues = json.loads(projectIssues)


# We will append,all issues,in a list object.

listAllIssues = []


# The Issue details, we are interested in,

# are "Key" , "Summary" and "Reporter Name"

keyIssue, keySummary, keyReporter = "", "", ""



def iterateDictIssues(oIssues, listInner):

    # Now,the details for each Issue, maybe

    # directly accessible, or present further,

    # in nested dictionary objects.

    for key, values in oIssues.items():


        # If key is 'fields', get its value,

        # to fetch the 'summary' of issue.

        if key == "fields":


            # Since type of object is Json str,

            # convert to dictionary object.

            fieldsDict = dict(values)


            # The 'summary' field, we want, is

            # present in, further,nested dictionary

            # object. Hence,recursive call to

            # function 'iterateDictIssues'.

            iterateDictIssues(fieldsDict, listInner)


        # If key is 'reporter',get its value,

        # to fetch the 'reporter name' of issue.

        elif key == "reporter":


            # Since type of object is Json str

            # convert to dictionary object.

            reporterDict = dict(values)


            # The 'displayName', we want,is present

            # in,further, nested dictionary object.

            # Hence,recursive call to function 'iterateDictIssues'.

            iterateDictIssues(reporterDict, listInner)


        # Issue keyID 'key' is directly accessible.

        # Get the value of key "key" and append

        # to temporary list object.

        elif key == 'key':

            keyIssue = values

            listInner.append(keyIssue)


        # Get the value of key "summary",and,

        # append to temporary list object, once matched.

        elif key == 'summary':

            keySummary = values

            listInner.append(keySummary)


        # Get the value of key "displayName",and,

        # append to temporary list object,once matched.

        elif key == "displayName":

            keyReporter = values

            listInner.append(keyReporter)



# Iterate through the API output and look

# for key 'issues'.

for key, value in dictProjectIssues.items():


    # Issues fetched, are present as list elements,

    # against the key "issues".

    if key == "issues":


        # Get the total number of issues present

        # for our project.

        totalIssues = len(value)


        # Iterate through each issue,and,

        # extract needed details-Key, Summary,

        # Reporter Name.

        for eachIssue in range(totalIssues):

            listInner = []


            # Issues related data,is nested

            # dictionary object.

            iterateDictIssues(value[eachIssue], listInner)


            # We append, the temporary list fields,

            # to a final list.

            listAllIssues.append(listInner)


# Prepare a dataframe object,with the final

# list of values fetched.

dfIssues = pd.DataFrame(listAllIssues, columns=["Reporter",

                                                "Summary",

                                                "Key"])


# Reframing the columns to get proper

# sequence in output.

columnTiles = ["Key", "Summary", "Reporter"]

dfIssues = dfIssues.reindex(columns=columnTiles)

print(dfIssues)

print(type(dictProjectIssues))

json_object = json.dumps(dictProjectIssues, indent = 4)

print(type(json_object))

print(json_object)


df_json = pd.read_json(json_object)

df_json.to_excel("FILE PATH TO STORE XLSX FILE/DATAFILE.xlsx")

Comments

Popular posts from this blog

Add, remove, search an item in listview in C#

Below is the C# code which will help you to add, remove and search operations on listview control in C#. Below is the design view of the project: Below is the source code of the project: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Treeview_control_demo {     public partial class Form2 : Form     {         public Form2()         {             InitializeComponent();             listView1.View = View.Details;                   }         private void button1_Click(object sender, EventArgs e)         {             if (textBox1.Text.Trim().Length == 0)...

Add worklog in Jira using Python

 Below is the Python code to add the worklog in Jira. You need to install a request library for this. Here is the code: import requests from requests.auth import HTTPBasicAuth import json url = "https://your jira address here/rest/api/2/issue/ticket_number/worklog" auth = HTTPBasicAuth("username", "jira access token") headers = {     "Accept": "application/json",     "Content-Type": "application/json" } payload = json.dumps({     "comment": {         "content": [             {                 "content": [                     {                         "text": "This is for QA Testing",                         "type": "text"                     } ...

Some GUI examples in Python using customtkinter

 Some GUI examples in Python using customtkinter import customtkinter import os from PIL import Image class ScrollableCheckBoxFrame(customtkinter.CTkScrollableFrame):     def __init__(self, master, item_list, command=None, **kwargs):         super().__init__(master, **kwargs)         self.command = command         self.checkbox_list = []         for i, item in enumerate(item_list):             self.add_item(item)     def add_item(self, item):         checkbox = customtkinter.CTkCheckBox(self, text=item)         if self.command is not None:             checkbox.configure(command=self.command)         checkbox.grid(row=len(self.checkbox_list), column=0, pady=(0, 10))         self.checkbox_list.append(checkbox)     def remove_item(self, it...