Crack the Code: Fetching Assigned Tickets in Jira Cloud Made Easy with Python

Crack the Code: Fetching Assigned Tickets in Jira Cloud Made Easy with Python

Overview :-

If you’ve ever found yourself sifting through countless tickets in Jira trying to pinpoint your assignments, you’re not alone. Jira Cloud, while robust, can sometimes feel like a labyrinth when it comes to managing and tracking tasks. However, Python, with its simplicity and power, can be your ally in this quest. In this blog post, I’ll guide you through the process of using Python to fetch your assigned tickets from Jira Cloud efficiently. This method not only saves time but also enhances your workflow, allowing you to focus more on solving problems rather than finding them.

Pre-requisites :-

Before diving into the code, there are a few things you need to have in place:

  • Python Installation: Ensure Python is installed on your system. Any version above 3.6 should work fine.

  • Jira Cloud Account: Obviously, you need access to a Jira Cloud account with permissions to view projects and issues.

  • API Token: You’ll need to generate an API token from your Jira Cloud. This token will authenticate your requests.

  • Library Installation: Install the jira Python library which simplifies interacting with the Jira API. You can install it using pip:

Process :-

Setting Up Your Environment

  • First, import the necessary modules and install the required packages
requests
pandas
base64
json
  • Login to your Atlassian Account → Go to Security → Click on Create and manage API tokens → Click on Create Api Token.

  • Save the below code in a file with .py extension. eg., jira_ticket_data.py

import requests
import pandas as pd
from datetime import datetime
from openpyxl import Workbook
import base64
import json

# Jira Configuration
JIRA_URL = 'https://mahira.atlassian.net'
JIRA_API_TOKEN = 'YOUR JIRA API-TOKEN'
JIRA_USER_EMAIL = 'your-jira email'
JIRA_JQL = 'status in ("Released", "Done")'

# Function to fetch issues from Jira
def fetch_issues(start_at=0, max_results=50):
    url = f'{JIRA_URL}/rest/api/3/search'
    auth = base64.b64encode(f'{JIRA_USER_EMAIL}:{JIRA_API_TOKEN}'.encode()).decode()
    headers = {
        'Authorization': f'Basic {auth}',
        'Content-Type': 'application/json'
    }
    params = {
        'jql': JIRA_JQL,
        'startAt': start_at,
        'maxResults': max_results,
        'fields': 'summary,assignee,created,status,project,sprint'
    }
    response = requests.get(url, headers=headers, params=params)

    if response.status_code != 200:
        print(f"Error {response.status_code}: {response.text}")

    response.raise_for_status()
    return response.json()

# Fetch all issues from Jira
def fetch_all_issues():
    issues = []
    start_at = 0
    max_results = 50
    total = 1  # Initialize with a non-zero value to enter the loop

    while start_at < total:
        data = fetch_issues(start_at, max_results)
        issues.extend(data['issues'])
        total = data['total']
        start_at += max_results
    return issues

# Process issues and group by sprint and assignee
def process_issues(issues):
    rows = []

    for issue in issues:
        created_date = issue['fields']['created']
        created_date = datetime.strptime(created_date, '%Y-%m-%dT%H:%M:%S.%f%z')
        month = created_date.strftime('%Y-%m')
        assignee = issue['fields']['assignee']['displayName'] if issue['fields']['assignee'] else 'Unassigned'
        project = issue['fields']['project']['name']
        sprint = issue['fields'].get('sprint', {}).get('name', 'No Sprint')
        rows.append([project, issue['key'], issue['fields']['summary'], assignee, created_date, month, sprint])

    df = pd.DataFrame(rows, columns=['Project', 'Key', 'Summary', 'Engineer Name', 'Created', 'Month', 'Sprint'])
    grouped = df.groupby(['Month', 'Sprint', 'Project', 'Engineer Name']).size().reset_index(name='Total No.of Tickets Worked on')
    return grouped

# Export to Excel
def export_to_excel(df, filename='jira_tickets.xlsx'):
    with pd.ExcelWriter(filename, engine='openpyxl') as writer:
        df.to_excel(writer, index=False, sheet_name='Jira Issues')

if __name__ == '__main__':
    issues = fetch_all_issues()
    grouped_issues = process_issues(issues)
    export_to_excel(grouped_issues)
    print(f'Exported {len(grouped_issues)} records to Excel.')
JIRA_JQL = 'status in ("Released", "Done")'
  • Update the email, api-token and jira_url with your specified values.

  • Open a command prompt oe terminal window and run

python3 jira_tickets_data.py

Conclusion :-

Using Python to interact with Jira Cloud for fetching assigned tickets not only streamlines your workflow but also opens up a plethora of possibilities for automating and optimizing your issue management process. Whether you’re a developer, a project manager, or just someone looking to get more organized, integrating Python with Jira Cloud can significantly boost your productivity. So, give it a try, and you might just wonder how you managed without it.