Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in

Python code for Jira REST API Sharing

Jacob Haskamp December 8, 2022

Hello, 

I wanted to share some of my Python code to the community as well as give the opportunity for anyone whom wants to also share their code. Support seems to be slim and a post like this would've been very helpful when I first started using the API. 

 

Notes: 
No this isn't the whole script just useful snippets.
My script uses a Machine Learning algorithm I wrote to analyze all of our tickets and predict the correct assignee.
When a ticket comes in and it isn't automatically assigned the ML Model gathers the tickets data, predicts the assignee, and alters the summary, comments, and reassigns to the new user. 
The data is then fed back into the ML model based on if the user uses a report link to tell the model if the guess was wrong. This is just the parts that directly interact with Jira

See below functions and pick what's best for you:

How to login to Jira with python and JSON, then save cookies:

    def login(session, USERNAME, PASSWORD):
        '''
        Returns the cookies after logging in
        '''
        # Attempt to login to Jira
        response = session.post('https://jira.**********.com/login.jsp', data={
            'os_username': USERNAME,
            'os_password': PASSWORD
        }, allow_redirects=False)
        return response.cookies
How to get a tickets information from a specific ticket link:
 def Get_ticket_Info():
            soup = BeautifulSoup(response.content, 'lxml')
            ticket_name = soup.find_all('td', class_ = 'issuekey')
            ticket_summary = soup.find_all('td', class_='summary')
            ticket_reporter = soup.find_all('td', class_='reporter')
            ticket_description = soup.find_all('td', class_='description')
            name_data = []
            reporter_data = []
            summary_data = []
            description_data = []
            df = pd.DataFrame(columns = ['Name','Reporter','Summary','Description'])
            processed_list = os.listdir(processed_folder)
            for x in range(len(ticket_reporter)):
                if ((str(ticket_name[x].text.strip()+'.txt'))) in processed_list:
                    #print("Ticket", ticket_name[x],"exists in processed folder.")
                    break
                name_data.append(ticket_name[x].text.strip())
                reporter_data.append(ticket_reporter[x].text.strip())
                summary_data.append(ticket_summary[x].text.strip())
                if ticket_description[x].text:
                    description_data.append(ticket_description[x].text.strip())
                else:
                    description_data.append(str('the'))
            df['Reporter'] = reporter_data
            df['Summary'] = summary_data
            df['Description'] = description_data
            df['Name'] = name_data
            return df
Get the API Link for each ticket :
    def Get_Comment_Link(ticket_url = 'Error, link required.'):
        response2 = session.get(ticket_url, cookies=cookies, allow_redirects=False)
        soup = BeautifulSoup(response2.content, 'lxml')
        index_code = soup.find_all('div', class_ = 'sd-comment-issue-page-edit-root')
        parse_text = index_code
        parse_text = str(parse_text)
        parse_text = parse_text.split(':')
        parse_text = parse_text[1]
        parse_text = re.sub('[^0-9]','', parse_text)
        custom_link = ('https://jira.**********.com/rest/api/2/issue/'+parse_text+'/comment')
        return custom_link

    def Get_Assignee_Link(ticket_url = 'Error, link required.'):
        response2 = session.get(ticket_url, cookies=cookies, allow_redirects=False)
        soup = BeautifulSoup(response2.content, 'lxml')
        index_code = soup.find_all('div', class_ = 'sd-comment-issue-page-edit-root')
        parse_text = index_code
        parse_text = str(parse_text)
        parse_text = parse_text.split(':')
        parse_text = parse_text[1]
        parse_text = re.sub('[^0-9]','', parse_text)
        custom_link = ('https://jira.**********.com/rest/api/2/issue/'+parse_text+"/assignee")
        return custom_link

    def Get_Summary_Link(ticket_url = 'Error, link required.'):
        response2 = session.get(ticket_url, cookies=cookies, allow_redirects=False)
        soup = BeautifulSoup(response2.content, 'lxml')
        index_code = soup.find_all('div', class_ = 'sd-comment-issue-page-edit-root')
        parse_text = index_code
        parse_text = str(parse_text)
        parse_text = parse_text.split(':')
        parse_text = parse_text[1]
        parse_text = re.sub('[^0-9]','', parse_text)
        custom_link = ('https://jira.**********.com/rest/api/2/issue/'+parse_text)
        return custom_link
How to post to a ticket using above Jira API Link:
    def Send_Assignee(comment, URL):

            request2 = session.put(URL, cookies=cookies, json = {
               
                "name":"assignee_emailgoeshere***********"
       
            })
            #soup = BeautifulSoup(response2.content, 'lxml')
            print("Request status code is ", request2.status_code)
               

    def Send_Summary(comment, URL, summary):

        request2 = session.put(URL, cookies=cookies, json = {
           
            "fields": {"summary": summary}
   
        })
        #soup = BeautifulSoup(response2.content, 'lxml')
        print("Request status code is ", request2.status_code)
        print("Summary of the ticket should be changed to ", summary)

    def Send_Comment(comment, URL):

        request2 = session.post(URL, cookies=cookies, json = {
           
    "body": comment,
        })
        #soup = BeautifulSoup(response2.content, 'lxml')
        print("Request status code is ", request2.status_code)
Libraries I used: 
from distutils.log import Log
from email import header
import json
from multiprocessing.dummy import Process
from smtpd import DebuggingServer
import requests
from pprint import pprint
import datetime
from bs4 import BeautifulSoup
import pandas as pd
import numpy as np
import os
import tensorflow as tf
from keras.models import load_model
import pickle
import re, string
import nltk
from nltk.corpus import stopwords
stop = stopwords.words('english')
from nltk.stem import PorterStemmer, WordNetLemmatizer
porter_stemmer = PorterStemmer()
import shutil
import schedule
import time
from csv import writer
import random
Last Notes:
I'm willing to help if you have questions, but obv there is only so much time I have so please review the above carefully, especially the difference between post and put. A helpful few links are here for those struggling: 

1 comment

Comment

Log in or Sign up to comment
Grant.Smith December 8, 2022

Super cool! Thanks for sharing.

Like Jacob Haskamp likes this
Jacob Haskamp December 9, 2022

My pleasure, hope it helps someone on day :) 

TAGS
AUG Leaders

Atlassian Community Events