0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでシンプルにjiraからチケット情報を取得する

Last updated at Posted at 2024-07-28

はじめに

現場がJiraを使っていて、気に入ったからAPIの使い方をさらっておきたい

記事自体は随分前にQiitaに下書きしてあったもので、ついでにリファクタリングして記事公開

参考

Jira APIと戯れる 〜チケット情報取得編〜
JIRA REST API reference

ライブラリのインストール

Jira側でAPIトークンの生成

image.png
image.png
image.png
image.png
image.png

source

vietnam_research/domain/valueobject/jira.py
import re
from dataclasses import dataclass


@dataclass(frozen=True)
class EmailAddress:
    email: str

    def __post_init__(self):
        if not self._validate_email(self.email):
            raise ValueError("Invalid email format!")

    @staticmethod
    def _validate_email(email: str):
        pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
        if re.match(pattern, email):
            return True
        return False


@dataclass(frozen=True)
class Project:
    key: str
    name: str


@dataclass(frozen=True)
class Issue:
    key: str
    name: str
    description: str

    def __post_init__(self):
        if not self._validate_issue_id(self.key):
            raise ValueError("Invalid issue id format!")

    @staticmethod
    def _validate_issue_id(issue_id: str):
        # The issue_id usually looks like "XYZ-1". Modify this regex for your needs
        pattern = r"[A-Z]+-\d+"
        if re.match(pattern, issue_id):
            return True
        return False

jira_.py という名前にしているのはインストールしたライブラリの名前 jira と名前被りしてサーキュラーインポートになるから

vietnam_research/domain/service/jira_.py
import os

from jira import JIRA, JIRAError

from vietnam_research.domain.valueobject.jira import (
    EmailAddress,
    Project,
    Issue,
)

JIRA_SERVER = "https://henojiya.atlassian.net"


def get_all_projects(mail: EmailAddress) -> list[Project]:
    jira_token = os.environ.get("JIRA_TOKEN")
    jira_instance = JIRA(JIRA_SERVER, basic_auth=(mail.email, jira_token))

    return [Project(x.key, x.name) for x in jira_instance.projects()]


def get_all_issues(mail: EmailAddress) -> list[Issue]:
    jira_token = os.environ.get("JIRA_TOKEN")
    jira_instance = JIRA(JIRA_SERVER, basic_auth=(mail.email, jira_token))

    temp = jira_instance.search_issues("project=HEN", maxResults=False)
    return [Issue(x.key, x.fields.summary, x.fields.description) for x in temp]


# TODO: チケットを作成する機能を作る
def retrieve_specific_issue(issue_key: str, mail: EmailAddress) -> Issue:
    jira_token = os.environ.get("JIRA_TOKEN")
    jira_instance = JIRA(JIRA_SERVER, basic_auth=(mail.email, jira_token))

    try:
        temp = jira_instance.issue(issue_key)
        return Issue(temp.key, temp.fields.summary, temp.fields.description)
    except JIRAError as e:
        raise ValueError(e.text)


if __name__ == "__main__":
    email = EmailAddress(os.environ.get("EMAIL_HOST_USER"))
    project_list = get_all_projects(email)
    for project in project_list:
        print(project)

    issue_list = get_all_issues(email)
    print(issue_list)

    retrieve_the_issue = retrieve_specific_issue("HEN-1", email)
    print(retrieve_the_issue)

確認

チケットを作って

  • HEN-1 というチケットが作成された
    image.png
console
runfile('C:\\Users\\xxxx\\OneDrive\\dev\\portfolio\\vietnam_research\\domain\\service\\jira_service.py', wdir='C:\\Users\\xxxx\\OneDrive\\dev\\portfolio\\vietnam_research')
Project(key='HEN', name='henojiya')
[Issue(key='HEN-1', name='練習のチケット', description='練習のチケットの説明です')]
Issue(key='HEN-1', name='練習のチケット', description='練習のチケットの説明です')
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?