Rest api with ruby » History » Version 10
Toshi MARUYAMA, 2016-04-25 15:28
gem 'activeresource'
| 1 | 1 | Jean-Philippe Lang | h1. Using the REST API with Ruby |
|---|---|---|---|
| 2 | |||
| 3 | Redmine REST API follows the Rails's RESTful conventions, so using it with "ActiveResource":http://api.rubyonrails.org/classes/ActiveResource/Base.html is pretty straightforward. |
||
| 4 | |||
| 5 | 4 | Eric Davis | h2. ActiveResource |
| 6 | |||
| 7 | 10 | Toshi MARUYAMA | On Redmine 3.x (Rails 4.2), you need to add 'activeresource' gem. |
| 8 | For example, at Gemfile.local: |
||
| 9 | <pre><code class="ruby"> |
||
| 10 | gem 'activeresource' |
||
| 11 | </code></pre> |
||
| 12 | |||
| 13 | 1 | Jean-Philippe Lang | Here is a simple ruby script that demonstrates how to use the Redmine REST API: |
| 14 | |||
| 15 | <pre> |
||
| 16 | <code class="ruby"> |
||
| 17 | require 'rubygems' |
||
| 18 | require 'active_resource' |
||
| 19 | |||
| 20 | # Issue model on the client side |
||
| 21 | class Issue < ActiveResource::Base |
||
| 22 | self.site = 'http://redmine.server/' |
||
| 23 | self.user = 'foo' |
||
| 24 | self.password = 'bar' |
||
| 25 | end |
||
| 26 | |||
| 27 | # Retrieving issues |
||
| 28 | issues = Issue.find(:all) |
||
| 29 | puts issues.first.subject |
||
| 30 | |||
| 31 | # Retrieving an issue |
||
| 32 | issue = Issue.find(1) |
||
| 33 | puts issue.description |
||
| 34 | puts issue.author.name |
||
| 35 | |||
| 36 | # Creating an issue |
||
| 37 | 2 | Jean-Philippe Lang | issue = Issue.new( |
| 38 | :subject => 'REST API', |
||
| 39 | :assigned_to_id => 1, |
||
| 40 | 7 | Denis Savitskiy | :project_id => 1 |
| 41 | 9 | Marcin Garski | # custom field with id=2 exist in database |
| 42 | :custom_fields => [{id: 2, value: "IT"}] |
||
| 43 | 7 | Denis Savitskiy | ) |
| 44 | 1 | Jean-Philippe Lang | if issue.save |
| 45 | puts issue.id |
||
| 46 | else |
||
| 47 | puts issue.errors.full_messages |
||
| 48 | end |
||
| 49 | 9 | Marcin Garski | |
| 50 | 1 | Jean-Philippe Lang | |
| 51 | # Updating an issue |
||
| 52 | issue = Issue.find(1) |
||
| 53 | issue.subject = 'REST API' |
||
| 54 | issue.save |
||
| 55 | |||
| 56 | # Deleting an issue |
||
| 57 | issue = Issue.find(1) |
||
| 58 | 8 | Toshi MARUYAMA | #issue.destroy |
| 59 | 1 | Jean-Philippe Lang | </code> |
| 60 | </pre> |
||
| 61 | 6 | Geoffroy Planquart | |
| 62 | _You may need to set @include_root_in_json = true@ in your ActiveResource class_ |