Jira api python auth

How to GET All Issues with the Jira API in Python

Jira is one of the best-known tools in the software industry for tracking work items. Originally created for bug and issue tracking, it has evolved into a more general workflow management tool. Jira can be used for IT service management, project management, planning, and tracking bugs. It’s also flexible enough to let you track custom workflows like HR management processes or sales processes.

As an increasing number of people in your organization use Jira to track more things, you’ll likely want to use APIs to interact with it to extract data automatically. One of the benefits of Jira is that its REST API lets you get issues from different projects. You can use this data to analyze issues from different projects and create centralized data analytics.

In this article, you’ll learn how to use the Jira REST API to write issues from Jira into a CSV file by using a simple Python script and by using a Jira webhook with a Python Flask application. You can get the sample code used in this tutorial on the following GitHub repository.

Getting Issues from Jira Using Python

This tutorial shows you how to interact with Jira to extract data from your project and save them in a CSV file.

Jira API Authentication

The Jira REST API has security measures to protect your data. Its different authentication options depend on the configuration of your Jira instance. A common authentication method is using an API token, which is what this tutorial uses.

To access your Jira instance with this method, you need to create an API token. Go to the following URL, click on API tokens , and then click on Create API token.

Create API token screen

A new pop-up will appear that contains the token but with it hidden. Click on Copy, and save this token somewhere in your notes because you will need it later.

Jira API token

Keep the token safe since it can give others access to your Jira instance with your permissions.

List API tokens screen

Preparation

To follow along with this tutorial, you’ll need Python installed on your local machine. You’ll also need to create a new project in your Jira instance with some issues with which to test your script.

Go to Projects > Create Project and choose a template that you would like to use. For this tutorial, choose Software Development as the template and Kanban. Next, click on Use template and Select a team managed project.

Use template

Set TTO as the project key and name your project «Team Onboarding».

Create Jira project

Jira project overview

Now that you have your project set up, you’ll write some code to interact with Jira using Python.

Читайте также:  Javascript reference file object

Reading Data from Jira

Open your terminal and install the following Python library using pip.

You will use the requests package to access Jira using the search REST API endpoint.

Create a new Python file named JiraBoard.py and paste the following code into it:

", "") headers = < "Accept": "application/json" >query = < 'jql': 'project = TTO' >response = requests.request( "GET", url, headers=headers, params=query, auth=auth ) data = json.loads(response.text) selectedIssues=[] #Get all issues and put them into an array for issue in data['issues']: #print(issue) selectedIssues.append(issue) #Save data from Jira into a csv file with open('issues.csv', 'w', newline='') as csvfile: fieldnames = ['expand', 'key', 'id', 'fields', 'self'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) for issue in selectedIssues: writer.writerow(issue) JiraBoard() 

CSV Jira issues

Jira Webhook

Webhooks are used to synchronize data between two systems to make the data flow between these systems in real time. For example, if you have Freshdesk or Zoho as a CRM, you might want to integrate it with Jira to push issues reported by your customers to your board on Jira for the technical team to investigate.

To create a webhook using Jira, you first need to have a public URL of our application. When you create or update an issue, Jira will push these changes to the webhook URL that you will specify. To do so, you either have to host a Python application on the cloud, or you can expose your application publicly. To keep it simple, you won’t be hosting your application on the cloud for this tutorial; you’ll use a tool to expose your application publicly.

Flask Application

The above code defines a simple Python flask application with two HTTP routes. The first route is the default one, which returns a simple welcome text. The second route is

Open your terminal, and run the following command to run the flask application:

Running Flask application

Your application is now running on your localhost, which is http://127.0.0.1:5000/. When you open the URL in your web browser, you should see this home page:

Flask application home page

Next, go to the webhook URL on your browser, which is http://127.0.0.1:5000/webhook. You should see the message Retrieving issues is completed, meaning that the code finished and the

Flask application webhook pageCSV file generated

Exposing Your Application Publicly

Now that you have your application ready, you need to expose the application publicly so you can use it with the Jira webhook. To do so, you need to set up ngrock on your machine following the instructions from their website.

After you finish installing ngrock, open your terminal and run the following command:

After running the command, you should see the URL that will redirect your localhost:5000 port to a public URL. Check the forwarding field and open the link that ends with

ngrock outputApplication exposed publicly

Public webhook route

Create a Webhook with Request Bin

When a change happens on your Jira board, the change will call a webhook, then the webhook will initiate a workflow that you’ll define, which is, in this case, calling your local Flask application. To do so, you will use RequestBin, a tool used to create webhooks.

To start, create an account, and log in to the dashboard.

Читайте также:  Программа html to xml

RequestBin dashboard

Go to the workflow section, click on New +, and select the HTTP/Webhook option.

RequestBin webhook

Next, select HTTP Requests and click on Save and continue. A unique URL will appear that you’ll use to trigger the workflow. Take note of this URL because you’ll need it in the next step.

Workflow URL

Click on + to add the next step, which will indicate what will happen once this workflow is triggered. In this case, you’ll add a simple HTTP request to call the Flask application. Select Send any HTTP Request, and add the public link of the Flask application generated with ngrock.

RequestBin Send HTTP Request

Finally, click on Deploy so that the workflow is deployed and ready.

Set Up Jira

Now you’re ready to set up your Jira webhook. To create a webhook on Jira, go to the settings menu in the top right and select System from the drop-down menu items:

Jira settings

Next, go to Webhooks on the left navigation bar, and click on Create a webhook:

Jira webhook

Fill in the details: use «Jira Webhook» as the name and the URL you got from RequestBin.

For the configuration on when the webhook should be called, select created, updated, and deleted under Issue. Scroll to the bottom and click on Create.

Jira webhook configuration

And, congratulations! You’re done creating your webhook with Jira.

Jira webhook successfully created

Testing

Now that you have everything set, go to your Jira board and create or update some issues to test your solution.

If you do, you should see the request intercepted on RequestBin, the workflow triggered, and your Flask application app called. You should also see the

Jira dashboardRequestBin dashboard

Accessing Multiple Jira Instances or Other Similar Data Sources

As you increase your Jira usage, especially in a bigger organization, you might want to integrate different Jira instances with each other or connect to other data sources.

For example, if you’re using ServiceNow for your IT service management processes, you might want to correlate ServiceNow incidents with items in your Jira instance. ServiceNow also offers a REST API that you could connect to. However, it would be difficult to maintain both implementations and connections. You’d need to map between different API responses manually as the response structure from the Jira REST API is not the same as the return structure from ServiceNow. Your scripts would also need to talk to at least two endpoints.

This is where tools like Merge are able to help. Their unified API lets you connect various data sources through setting up the connectivity in Merge. Merge supports various third-party APIs out of the box, especially for ticketing but also for HR management systems.

Interacting with the Merge API is as simple as interacting with the Jira REST API, but you can connect various integrations in the backend. Merge takes care of handling the connection to the backend services and returns results in the same structure across various providers. As an example, the Ticket object that the Merge API offers can be mapped to ServiceNow and Jira issues, which makes it easier for your script to handle the responses.

Читайте также:  What are data types in javascript

Conclusion

This article showed you how to interact with and export information from the Jira REST API using Python. You also learned how to set up a Jira webhook for newly created issues in Jira.

As your integration needs grow, Merge lets you centralize access to different tools and systems through a unified API. Merge comes with hundreds of out-of-the-box integrations with HR, recruiting, ticketing, CRM, marketing automation, and accounting platforms to help B2B companies speed up the integration of their systems.

Источник

Работа с Jira API при помощи Python

Всем привет. Появилась мысль автоматизировать выгрузку отчетов из Jira. Так как любимым инструментом был Python, выбор пал на модуль от JIra позволяющий работать с их API. Кому интересно прошу по кат.

image

У atlassian есть официальная документация по использованию их модуля. Сам модуль так и называется «jira». По традиции выполним установку модуля командой:

Затем импортируем модуль непосредственно в коде:

Для того чтобы подключиться к самому серверу, необходимо создать клиент передав в него требуемые параметры:

jira_options = jira = JIRA(options=jira_options, basic_auth=(login, api_key))

Для того чтобы пройти авторизацию по паролю, вместо api key можно передать пароль. После того как авторизация пройдена, мы имеем активный api client к которому можно обращаться.

Возможности конечно не безграничны, но достаточно широкие. Мне было необходимо вытаскивать задачи за определенную неделю и составлять отчет по потраченным часам в Excell. Вытаскивать задачи можно непосредственно по самому проекту, по номеру задачи, так и по JQL запросу. Инструменты поиска достаточно гибкие и простые. Вся информация возвращаемая апи клиентом приходит в string, поэтому для работы с ней требуются дополнительные действия.
Составляем jql запрос и забираем по нему задачи:

jql = 'project = ' + project_key + ' AND worklogDate >= ' + work_date issues_list = jira.search_issues(jql) 

К сожалению я так и не понял почему в тех задачах которые получаются через такой запрос нет свойства worklog. После некоторых попыток понять что же не так, я вежливо попросил у jira задачу по номеру:

issue = jira.issue(issue_key)

В задаче возвращенной по такому методу поле worklog со списком worklog-ов было. В результате чего я стал брать задачи по jql запросу, вытаскивал номера задачи и уже после вытаскивал необходимую мне информацию:

worklogs = issue.fields.worklog.worklogs

Подобная строка позволяет вытащить все записи о времени от определенной задачи. У каждой из записи есть информация о времени как в секундах так и в текстовом представлении (1h, 3d etc).
Дальше все просто, берем отбрасываем записи, которые не подходят по периоду, в моем случае не совпадает номер недели:

worklog_date_str = re.search(r'(\d-\d-\d)', worklog.started) worklog_date = datetime.strptime(worklog_date_str.group(0), '%Y-%m-%d') if worklog_date.isocalendar()[1] == weak_number:

Так как дата возвращается в строке, я воспользовался простым регулярным выражением, чтобы забирать его, а в следующей строке привожу уже необходимый тип. Выражение worklog_date.isocalendar()[1] позволяет узнать номер недели, который будет сравниваться с тем что необходимо забирать. Если он совпадает, топаем дальше и записываем остальные данные.

В целом вышеприведенный модуль позволяет решать достаточно широкий круг задач, нужно лишь время и желание.

Можно не запрашивать задачи повторно, а просто экспандить нужное поле
github.com/pycontribs/jira/blob/master/jira/client.py#L2371
спасибо HSerg

Источник

Оцените статью