LoginSignup
0
0

More than 5 years have passed since last update.

RubyのFaradayを使ってJIRA APIを操作してみる

Posted at

やってみたこと

  • Jiraチケットの作成
  • 作成したチケットへのコメント投下
  • 作成したチケットのクローズ

基本的に以下のURLをみながら実装
JIRA Cloud REST API Reference
はじめての JIRA REST API
モデルで実装してrailsに機能追加

Jiraチケットの作成

jira_api.rb
class JiraApi

  def initialize
    @jira_host_url = 'https://<jira_hostname>'
    @conn_jira = Faraday::Connection.new(:url => @jira_host_url) do |builder|
      builder.request :url_encoded # リクエストパラメータを URL エンコードする
      builder.request :basic_auth, "AUTH_MAIL", "AUTH_PASS"
      #builder.response :logger # リクエストを標準出力に出力する
      builder.adapter :net_http # Net/HTTP をアダプターに使う
      #builder.request :retry, max: 10, interval: 0.01 #リトライする場合
    end
  end


  def create_issue(body)

    _hash = {
        "fields" => {
            "project" => {
                "key" => "TEST_PJ"
            },
            "summary" => "【自動チケット作成】test",
            "assignee" => {
                "name" => "REPORTER_MAIL"
            },
            "priority" => {
                "id" => "3"
            },
            "description" => "#{body}",
            "reporter" => {
                "name" => "REPORTER_MAIL"
            },
            "timetracking" => {
                "originalEstimate" => "60"
            }
        }
    }

    res = @conn_jira.post do |req|
      req.url "/rest/api/2/issue"
      req.headers['Content-Type'] = 'application/json'
      req.body = JSON.pretty_generate(_hash)
    end

    @jira_id = JSON.load(res.body)['key']
    @jira_url = "#{@jira_host_url}/browse/#{@jira_id}"
    return res.status.between?(200, 299), @jira_url, @jira_id
  end

  ...
end

作成したチケットへのコメント投下

jira_api.rb
class JiraApi
  ...

  def add_comment(comment)
    _hash = {
        "body" => comment
    }
    res = @conn_jira.post do |req|
      req.url "rest/api/2/issue/#{JIRA_ISSUE_ID}/comment"
      req.headers['Content-Type'] = 'application/json'
      req.body = JSON.pretty_generate(_hash)
    end
    return res.status.between?(200, 299)
  end

 ...
end

作成したチケットのクローズ

jira_api.rb
class JiraApi
  ...

  def close_issue
    _hash = {
        "transition" => {
            "id" => "2"
        }
    }
    res = @conn_jira.post do |req|
      req.url "rest/api/2/issue/#{JIRA_ISSUE_ID}/transitions"
      req.headers['Content-Type'] = 'application/json'
      req.body = JSON.pretty_generate(_hash)
    end
    print res.status
    return res.status.between?(200, 299)
  end

end

transitionのid番号が何に対応するかは
https://<jira_hostname>/rest/api/2/issue/#{JIRA_ISSUE_ID}/transitions
にGETリクエストを送ると調べられるます

感想

いろんな種類のapiが揃っていてかなり色々な使い方ができそう
今回のwebアプリではjiraのチケットを作業ログ代わりに使うことで、
様々な人がみやすい形で残すことができた

0
0
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
0