DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Building Data Pipelines With Jira API
  • Automation of Product Development Processes
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)

Trending

  • Why Database Migrations Take Months and How to Speed Them Up
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  • Beyond Simple Responses: Building Truly Conversational LLM Chatbots
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Use the Jira API

How to Use the Jira API

In this post, we will explore the Jira Rest API and explain how to use the Jira API in order to generate a user-based time report.

By 
Gunter Rotsaert user avatar
Gunter Rotsaert
DZone Core CORE ·
Mar. 11, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
24.5K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will explore the Jira Rest API. We will explain how you can use the Jira API in order to generate a user-based time report. Besides that, it is a good excuse to do some Python coding.

Introduction

A lot of companies are using Jira nowadays in order to support their Scrum or Kanban process. Add-ons can be installed for extending the functionality of Jira. Some of them are free, other ones need to be purchased. Jira is available in two versions, a Cloud version and a Server (on-premise) version. The number of add-ons for Jira Cloud is very limited and aims at smaller teams, Jira Server has many more add-ons and aims at larger organizations. 

The number of add-ons and whether you want to be responsible for maintenance yourself can be decisive factors on which version to use. However, both versions also support an API. It is quite an extended API and gives you the opportunity to write your own scripts extending the Jira functionality. For example, you can create an interface between your Service Management system and Jira for passing tickets from 1st line support (working with the Service Management system) to 2nd line support (working with Jira).

Enough for this introduction, let’s start using the API! We will develop a Python script that will generate a user-based time report for a specific Jira project. We are using Python 3.7.5 and version 2 of the Jira API. The sources can be found at GitHub.

Create a Jira Cloud Account

First things first, we will need a running instance of Jira in order to execute some integration tests. Go to the Jira website and navigate to the bottom of the page. We choose the free Jira Cloud plan.

In the next step, you need to create an account and choose a site name. We choose the mydeveloperplanet.atlassian.net site name.

The last thing to do is to create a Scrum board and then we are all set to go. It took us less than 5 minutes to get started with Jira Cloud.

Create some user stories with sub-tasks, start a sprint, and log some work to the sub-tasks. We can also use the Jira API to do so, but that is maybe something for another post.

The Jira API

Since we are using Jira Cloud, we need to create an API token first. Click on your avatar in the left bottom corner and choose ‘Account settings’.

Go to the Security tab and create the API token.

Now, let’s take a look at the Jira Rest API documentation: https://developer.atlassian.com/cloud/jira/platform/rest/v2/

The API is well documented and contains examples how to call the API with curl, Node.js, Java, Python and PHP. The expected response of the request is also provided. So, all of the documentation is available, the main challenge is to find out which requests you need for your application.

Beware that there is also documentation available for the Jira Server API. It contains less clear information than the Cloud version. Before writing a script which should support both versions, check whether the API call is identical and use the Cloud documentation if possible.

Note that it is also possible to use the Python Jira library, but we preferred to talk to the Jira API directly. This way, we are independent of a third party library.

The Jira Time Report

The requirements for the Jira time report we want to create, are the following:

  • The report must contain all the logged worked per user within a specified time period for a specific Jira project
  • The report must be sorted by user, day and issue

For retrieving the work logs of a Jira issue, we need to call the Get issue worklogs request. This request requires an issue Id or key. Therefore, we first need to retrieve the issues which contain work logs within the specified time period. We can use the Search for issues using JQL request for that. This will give us the possibility to use the Jira Query Language (JQL), just like we can use it for searching issues in Jira itself. We are using the following query:

Python
 




xxxxxxxxxx
1


 
1
query = {
2
    'jql': 'project = "' + args.project + '" and timeSpent is not null and worklogDate >= "' + args.from_date +
3
                      '"' + ' and worklogDate < "' + convert_to_date(args).strftime("%Y-%m-%d") + '"',
4
    'fields': 'id,key',
5
    'startAt': str(start_at)
6
}



The jql checks the Jira project, whether there is any time spent on this issue, and at the end, it checks whether work logs exists within the specified time period. The Jira project and date where to search from are given as arguments when starting the application. The from_date will have a time of 00:00:00. The convert_to_date will add one day to the to_date argument at time 00:00:00. When no to_date is given, it will be defaulted to tomorrow at time 00:00:00.

The fields indicate which fields we want to receive. If not provided, all fields are returned, but we are only interested in the id and the key. The start_at parameter will indicate from which record on we want to receive the results. The results are paginated (max 50 results currently), so we will need to do something in order to request the other pages.

We invoke the Jira request with the above query and load the JSON part in response_json. Remember that pagination is used, so we add the plain JSON issue results to the list which will hold all issues in line 3. We deliberately did not transform the JSON output into objects because we only need the id and key. We can always do so later on if we want to.

Python
 




xxxxxxxxxx
1


 
1
response = get_request(args, "/rest/api/2/search", query)
2
response_json = json.loads(response.text)
3
issues_json.extend(response_json['issues'])



Support for pagination is done in the next part. The JSON response holds the total number of issues that are returned from the query and the maximum results that are returned from the request. We read those fields from the response and then check whether the request must be invoked again with a new start_at parameter. This code and the code above are part of an endless while-loop. We break out of the loop when we processed all of the search results in line 7.

Python
 




xxxxxxxxxx
1


 
1
total_number_of_issues = int(response_json['total'])
2
max_results = int(response_json['maxResults'])
3
max_number_of_issues_processed = start_at + max_results
4
if max_number_of_issues_processed < total_number_of_issues:
5
    start_at = max_number_of_issues_processed
6
else:
7
    break



Retrieving the work logs works pretty much the same way. We retrieve the work logs of an issue and then process only the work logs, which fall within the given time period. The work logs are converted to WorkLog objects.

Python
 




xxxxxxxxxx
1


 
1
class WorkLog:
2
    def __init__(self, issue_key, started, time_spent, author):
3
        self.issue_key = issue_key
4
        self.started = started
5
        self.time_spent = time_spent
6
        self.author = author



The only thing left to do is to sort the list of work logs. We use sorted for this and by means of the attrgetter, we get the desired sorting.

Python
 




xxxxxxxxxx
1


 
1
sorted_on_issue = sorted(work_logs, key=attrgetter('author', 'started', 'issue_key'))



Last but not least, the sorted_on_issue list is used to format the work logs into the chosen output format, either console output, CSV file or Excel file. For the latter, we used the xlsxwriter Python library.

Python
 




xxxxxxxxxx
1
15


 
1
def output_to_excel(work_logs):
2
    try:
3
        workbook = xlsxwriter.Workbook(EXCEL_FILE_NAME)
4
        worksheet = workbook.add_worksheet()
5
        row = 0
6
 
7
        for work_log in work_logs:
8
            worksheet.write(row, 0, work_log.author)
9
            worksheet.write(row, 1, work_log.started.strftime('%Y-%m-%d'))
10
            worksheet.write(row, 2, work_log.issue_key)
11
            worksheet.write(row, 3, str(timedelta(seconds=work_log.time_spent)))
12
 
13
            row += 1
14
    finally:
15
        workbook.close()



Conclusion

We explored the Jira API in order to generate a time report per user in a given time period for a specific Jira project. The API is well-documented and quite easy to use. When searching for information about the Jira Rest API, you will be guided to the version 3 of the API. Beware that this version is currently in beta. Feel free to use the Jira time report generator and to request for any new features.

API Jira (software)

Published at DZone with permission of Gunter Rotsaert, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building Data Pipelines With Jira API
  • Automation of Product Development Processes
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!