项目作者: sumoheavy

项目描述 :
JIRA REST API的Ruby gem
高级语言: Ruby
项目地址: git://github.com/sumoheavy/jira-ruby.git
创建时间: 2011-12-07T05:35:35Z
项目社区:https://github.com/sumoheavy/jira-ruby

开源协议:MIT License

下载


JIRA API Gem

Code Climate
Build Status

This gem provides access to the Atlassian JIRA REST API.

Example usage

Jira Ruby API - Sample Usage

This sample usage demonstrates how you can interact with JIRA’s API using the jira-ruby gem.

Dependencies

Before running, install the jira-ruby gem:

  1. gem install jira-ruby

Sample Usage

Connect to JIRA
Firstly, establish a connection with your JIRA instance by providing a few configuration parameters:
There are other ways to connect to JIRA listed below | Personal Access Token

  • private_key_file: The path to your RSA private key file.
  • consumer_key: Your consumer key.
  • site: The URL of your JIRA instance.
  1. options = {
  2. :private_key_file => "rsakey.pem",
  3. :context_path => '',
  4. :consumer_key => 'your_consumer_key',
  5. :site => 'your_jira_instance_url'
  6. }
  7. client = JIRA::Client.new(options)

Retrieve and Display Projects

After establishing the connection, you can fetch all projects and display their key and name:

  1. projects = client.Project.all
  2. projects.each do |project|
  3. puts "Project -> key: #{project.key}, name: #{project.name}"
  4. end

Handling Fields by Name

The jira-ruby gem allows you to refer to fields by their custom names rather than identifiers. Make sure to map fields before using them:

  1. client.Field.map_fields
  2. old_way = issue.customfield_12345
  3. # Note: The methods mapped here adopt a unique style combining PascalCase and snake_case conventions.
  4. new_way = issue.Special_Field

JQL Queries

To find issues based on specific criteria, you can use JIRA Query Language (JQL):

  1. client.Issue.jql(a_normal_jql_search, fields:[:description, :summary, :Special_field, :created])

Several actions can be performed on the Issue object such as create, update, transition, delete, etc:

Creating an Issue

  1. issue = client.Issue.build
  2. labels = ['label1', 'label2']
  3. issue.save({
  4. "fields" => {
  5. "summary" => "blarg from in example.rb",
  6. "project" => {"key" => "SAMPLEPROJECT"},
  7. "issuetype" => {"id" => "3"},
  8. "labels" => labels,
  9. "priority" => {"id" => "1"}
  10. }
  11. })

Updating/Transitioning an Issue

  1. issue = client.Issue.find("10002")
  2. issue.save({"fields"=>{"summary"=>"EVEN MOOOOOOARRR NINJAAAA!"}})
  3. issue_transition = issue.transitions.build
  4. issue_transition.save!('transition' => {'id' => transition_id})

Deleting an Issue

  1. issue = client.Issue.find('SAMPLEPROJECT-2')
  2. issue.delete

Other Capabilities

Apart from the operations listed above, this API wrapper supports several other capabilities like:
• Searching for a user
• Retrieving an issue’s watchers
• Changing the assignee of an issue
• Adding attachments and comments to issues
• Managing issue links and much more.

Not all examples are shown in this README; refer to the complete script example for a full overview of the capabilities supported by this API wrapper.

Running tests

Before running tests, you will need a public certificate generated.

  1. rake jira:generate_public_cert

Setting up the JIRA SDK

On Mac OS,

  1. ./bin/atlas-run-standalone --product jira

Once this is running, you should be able to connect to
http://localhost:2990/ and login to the JIRA admin system using admin:admin

You’ll need to create a dummy project and probably some issues to test using
this library.

Configuring JIRA to use OAuth

From the JIRA API tutorial

The first step is to register a new consumer in JIRA. This is done through
the Application Links administration screens in JIRA. Create a new
Application Link.
Administration/Plugins/Application Links

When creating the Application Link use a placeholder URL or the correct URL
to your client (e.g. http://localhost:3000), if your client can be reached
via HTTP and choose the Generic Application type. After this Application Link
has been created, edit the configuration and go to the incoming
authentication configuration screen and select OAuth. Enter in this the
public key and the consumer key which your client will use when making
requests to JIRA.

This public key and consumer key will need to be generated by the Gem user, using OpenSSL
or similar to generate the public key and the provided rake task to generate the consumer
key.

After you have entered all the information click OK and ensure OAuth authentication is
enabled.

For two legged oauth in server mode only, not in cloud based JIRA, make sure to Allow 2-Legged OAuth

Configuring JIRA to use HTTP Basic Auth

Follow the same steps described above to set up a new Application Link in JIRA,
however there is no need to set up any “incoming authentication” as this
defaults to HTTP Basic Auth.

Jira supports cookie based authentication whereby user credentials are passed
to JIRA via a JIRA REST API call. This call returns a session cookie which must
then be sent to all following JIRA REST API calls.

To enable cookie based authentication, set :auth_type to :cookie,
set :use_cookies to true and set :username and :password accordingly.

  1. require 'jira-ruby'
  2. options = {
  3. :username => 'username',
  4. :password => 'pass1234',
  5. :site => 'http://mydomain.atlassian.net:443/',
  6. :context_path => '',
  7. :auth_type => :cookie, # Set cookie based authentication
  8. :use_cookies => true, # Send cookies with each request
  9. :additional_cookies => ['AUTH=vV7uzixt0SScJKg7'] # Optional cookies to send
  10. # with each request
  11. }
  12. client = JIRA::Client.new(options)
  13. project = client.Project.find('SAMPLEPROJECT')
  14. project.issues.each do |issue|
  15. puts "#{issue.id} - #{issue.summary}"
  16. end

Some authentication schemes might require additional cookies to be sent with
each request. Cookies added to the :additional_cookies option will be added
to each request. This option should be an array of strings representing each
cookie to add to the request.

Some authentication schemes that require additional cookies ignore the username
and password sent in the JIRA REST API call. For those use cases, :username
and :password may be omitted from options.

Configuring JIRA to use Personal Access Tokens Auth

If your JIRA system is configured to support Personal Access Token authorization, minor modifications are needed in how credentials are communicated to the server. Specifically, the paremeters :username and :password are not needed. Also, the parameter :default_headers is needed to contain the api_token, which can be obtained following the official documentation from Atlassian. Please note that the Personal Access Token can only be used as it is. If it is encoded (with base64 or any other encoding method) then the token will not work correctly and authentication will fail.

  1. require 'jira-ruby'
  2. # NOTE: the token should not be encoded
  3. api_token = API_TOKEN_OBTAINED_FROM_JIRA_UI
  4. options = {
  5. :site => 'http://mydomain.atlassian.net:443/',
  6. :context_path => '',
  7. :default_headers => { 'Authorization' => "Bearer #{api_token}" },
  8. :auth_type => :basic
  9. }
  10. client = JIRA::Client.new(options)
  11. project = client.Project.find('SAMPLEPROJECT')
  12. project.issues.each do |issue|
  13. puts "#{issue.id} - #{issue.summary}"
  14. end

Using the API Gem in a command line application

Using HTTP Basic Authentication, configure and connect a client to your instance
of JIRA.

Note: If your Jira install is hosted on atlassian.net, it will have no context
path by default. If you’re having issues connecting, try setting context_path
to an empty string in the options hash.

  1. require 'rubygems'
  2. require 'pp'
  3. require 'jira-ruby'
  4. # Consider the use of :use_ssl and :ssl_verify_mode options if running locally
  5. # for tests.
  6. # NOTE basic auth no longer works with Jira, you must generate an API token, to do so you must have jira instance access rights. You can generate a token here: https://id.atlassian.com/manage/api-tokens
  7. # You will see JIRA::HTTPError (JIRA::HTTPError) if you attempt to use basic auth with your user's password
  8. username = "myremoteuser"
  9. api_token = "myApiToken"
  10. options = {
  11. :username => username,
  12. :password => api_token,
  13. :site => 'http://localhost:8080/', # or 'https://<your_subdomain>.atlassian.net/'
  14. :context_path => '/myjira', # often blank
  15. :auth_type => :basic,
  16. :read_timeout => 120
  17. }
  18. client = JIRA::Client.new(options)
  19. # Show all projects
  20. projects = client.Project.all
  21. projects.each do |project|
  22. puts "Project -> key: #{project.key}, name: #{project.name}"
  23. end

Using the API Gem in your Rails application

Using oauth, the gem requires the consumer key and public certificate file (which
are generated in their respective rake tasks) to initialize an access token for
using the JIRA API.

Note that currently the rake task which generates the public certificate
requires OpenSSL to be installed on the machine.

Below is an example for setting up a rails application for OAuth authorization.

Ensure the JIRA gem is loaded correctly

  1. # Gemfile
  2. ...
  3. gem 'jira-ruby', :require => 'jira-ruby'
  4. ...

Add common methods to your application controller and ensure access token
errors are handled gracefully

  1. # app/controllers/application_controller.rb
  2. class ApplicationController < ActionController::Base
  3. protect_from_forgery
  4. rescue_from JIRA::OauthClient::UninitializedAccessTokenError do
  5. redirect_to new_jira_session_url
  6. end
  7. private
  8. def get_jira_client
  9. # add any extra configuration options for your instance of JIRA,
  10. # e.g. :use_ssl, :ssl_verify_mode, :context_path, :site
  11. options = {
  12. :private_key_file => "rsakey.pem",
  13. :consumer_key => 'test'
  14. }
  15. @jira_client = JIRA::Client.new(options)
  16. # Add AccessToken if authorised previously.
  17. if session[:jira_auth]
  18. @jira_client.set_access_token(
  19. session[:jira_auth]['access_token'],
  20. session[:jira_auth]['access_key']
  21. )
  22. end
  23. end
  24. end

Create a controller for handling the OAuth conversation.

  1. # app/controllers/jira_sessions_controller.rb
  2. class JiraSessionsController < ApplicationController
  3. before_filter :get_jira_client
  4. def new
  5. callback_url = 'http://callback'
  6. request_token = @jira_client.request_token(oauth_callback: callback_url)
  7. session[:request_token] = request_token.token
  8. session[:request_secret] = request_token.secret
  9. redirect_to request_token.authorize_url
  10. end
  11. def authorize
  12. request_token = @jira_client.set_request_token(
  13. session[:request_token], session[:request_secret]
  14. )
  15. access_token = @jira_client.init_access_token(
  16. :oauth_verifier => params[:oauth_verifier]
  17. )
  18. session[:jira_auth] = {
  19. :access_token => access_token.token,
  20. :access_key => access_token.secret
  21. }
  22. session.delete(:request_token)
  23. session.delete(:request_secret)
  24. redirect_to projects_path
  25. end
  26. def destroy
  27. session.data.delete(:jira_auth)
  28. end
  29. end

Create your own controllers for the JIRA resources you wish to access.

  1. # app/controllers/issues_controller.rb
  2. class IssuesController < ApplicationController
  3. before_filter :get_jira_client
  4. def index
  5. @issues = @jira_client.Issue.all
  6. end
  7. def show
  8. @issue = @jira_client.Issue.find(params[:id])
  9. end
  10. end

Using the API Gem in your Sinatra application

Here’s the same example as a Sinatra application:

  1. require 'jira-ruby'
  2. class App < Sinatra::Base
  3. enable :sessions
  4. # This section gets called before every request. Here, we set up the
  5. # OAuth consumer details including the consumer key, private key,
  6. # site uri, and the request token, access token, and authorize paths
  7. before do
  8. options = {
  9. :site => 'http://localhost:2990/',
  10. :context_path => '/jira',
  11. :signature_method => 'RSA-SHA1',
  12. :request_token_path => "/plugins/servlet/oauth/request-token",
  13. :authorize_path => "/plugins/servlet/oauth/authorize",
  14. :access_token_path => "/plugins/servlet/oauth/access-token",
  15. :private_key_file => "rsakey.pem",
  16. :rest_base_path => "/rest/api/2",
  17. :consumer_key => "jira-ruby-example"
  18. }
  19. @jira_client = JIRA::Client.new(options)
  20. @jira_client.consumer.http.set_debug_output($stderr)
  21. # Add AccessToken if authorised previously.
  22. if session[:jira_auth]
  23. @jira_client.set_access_token(
  24. session[:jira_auth][:access_token],
  25. session[:jira_auth][:access_key]
  26. )
  27. end
  28. end
  29. # Starting point: http://<yourserver>/
  30. # This will serve up a login link if you're not logged in. If you are, it'll show some user info and a
  31. # signout link
  32. get '/' do
  33. if !session[:jira_auth]
  34. # not logged in
  35. <<-eos
  36. <h1>jira-ruby (JIRA 5 Ruby Gem) demo </h1>You're not signed in. Why don't you
  37. <a href=/signin>sign in</a> first.
  38. eos
  39. else
  40. #logged in
  41. @issues = @jira_client.Issue.all
  42. # HTTP response inlined with bind data below...
  43. <<-eos
  44. You're now signed in. There #{@issues.count == 1 ? "is" : "are"} #{@issues.count}
  45. issue#{@issues.count == 1 ? "" : "s"} in this JIRA instance. <a href='/signout'>Signout</a>
  46. eos
  47. end
  48. end
  49. # http://<yourserver>/signin
  50. # Initiates the OAuth dance by first requesting a token then redirecting to
  51. # http://<yourserver>/auth to get the @access_token
  52. get '/signin' do
  53. callback_url = "#{request.base_url}/callback"
  54. request_token = @jira_client.request_token(oauth_callback: callback_url)
  55. session[:request_token] = request_token.token
  56. session[:request_secret] = request_token.secret
  57. redirect request_token.authorize_url
  58. end
  59. # http://<yourserver>/callback
  60. # Retrieves the @access_token then stores it inside a session cookie. In a real app,
  61. # you'll want to persist the token in a datastore associated with the user.
  62. get "/callback" do
  63. request_token = @jira_client.set_request_token(
  64. session[:request_token], session[:request_secret]
  65. )
  66. access_token = @jira_client.init_access_token(
  67. :oauth_verifier => params[:oauth_verifier]
  68. )
  69. session[:jira_auth] = {
  70. :access_token => access_token.token,
  71. :access_key => access_token.secret
  72. }
  73. session.delete(:request_token)
  74. session.delete(:request_secret)
  75. redirect "/"
  76. end
  77. # http://<yourserver>/signout
  78. # Expires the session
  79. get "/signout" do
  80. session.delete(:jira_auth)
  81. redirect "/"
  82. end
  83. end

Using the API Gem in a 2 legged context

Here’s an example on how to use 2 legged OAuth:

  1. require 'rubygems'
  2. require 'pp'
  3. require 'jira-ruby'
  4. options = {
  5. :site => 'http://localhost:2990/',
  6. :context_path => '/jira',
  7. :signature_method => 'RSA-SHA1',
  8. :private_key_file => "rsakey.pem",
  9. :rest_base_path => "/rest/api/2",
  10. :auth_type => :oauth_2legged,
  11. :consumer_key => "jira-ruby-example"
  12. }
  13. client = JIRA::Client.new(options)
  14. client.set_access_token("","")
  15. # Show all projects
  16. projects = client.Project.all
  17. projects.each do |project|
  18. puts "Project -> key: #{project.key}, name: #{project.name}"
  19. end