Official Ruby Zendesk API Client
Latest commit 91e7a20 Feb 7, 2017 @bquorning bquorning committed on GitHub Merge pull request #319 from zendesk/bquorning/remove-scrub_rb
Remove dependency on scrub_rb

Zendesk API Client

API version support

This client only supports Zendesk's v2 API. Please see our API documentation for more information.


Please check out the wiki, class documentation, and issues before reporting a bug or asking for help.

Important Notices

  • Version 0.0.5 brings with it a change to the top-level namespace. All references to Zendesk should now use ZendeskAPI.
  • Version 0.3.0 changed the license from MIT to Apache Version 2.
  • Version 0.3.2 introduced a regression when side-loading roles on users. This was fixed in 0.3.4.
  • Version 1.0.0 changes the way errors are handled. Please see the wiki page for more info.
  • Version 1.3.0 updates the Faraday dependency to 0.9. Since Faraday did not bump a major version we have not either, but there is no guarantee >= 1.3.0 works with Faraday < 0.9
  • Version 1.3.8 had a bug where attachments were created, but the response was not handled properly
  • Version >= 1.0 and < 1.4.2 had a bug where non application/json response bodies were discarded
  • Version 1.5.0 removed support for Ruby 1.8
  • Version 1.6.0 ZendeskAPI::Voice::CertificationAddress is now ZendeskAPI::Voice::Address
  • Version 1.8.0 no longer considers 1XX and 3XX (except 304) response status codes valid and will raise a NetworkError
  • Version 1.x.x requires you to install scrub_rb or string-scrub or similar implementation of String#scrub! if you're using Ruby 1.9 or 2.0.


The Zendesk API client can be installed using Rubygems or Bundler.


gem install zendesk_api


Add it to your Gemfile

gem "zendesk_api"

and follow normal Bundler installation and execution procedures.

If you're using Ruby 1.9 or 2.0, you'll need an implementation of String#scrub!. You can use either scrub_rb or string-scrub or a similar gem to accomplish that:

gem "scrub_rb"


Configuration is done through a block returning an instance of ZendeskAPI::Client. The block is mandatory and if not passed, an ArgumentError will be thrown.

require 'zendesk_api'

client = do |config|
  # Mandatory:

  config.url = "<- your-zendesk-url ->" # e.g.

  # Basic / Token Authentication
  config.username = ""

  # Choose one of the following depending on your authentication choice
  config.token = "your zendesk token"
  config.password = "your zendesk password"

  # OAuth Authentication
  config.access_token = "your OAuth access token"

  # Optional:

  # Retry uses middleware to notify the user
  # when hitting the rate limit, sleep automatically,
  # then retry the request.
  config.retry = true

  # Logger prints to STDERR by default, to e.g. print to stdout:
  require 'logger'
  config.logger =

  # Changes Faraday adapter
  # config.adapter = :patron

  # Merged with the default client options hash
  # config.client_options = { :ssl => false }

  # When getting the error 'hostname does not match the server certificate'
  # use the API at

Note: This ZendeskAPI API client only supports basic authentication at the moment.


The result of configuration is an instance of ZendeskAPI::Client which can then be used in two different methods.

One way to use the client is to pass it in as an argument to individual classes.

note: all method calls ending in ! will raise an exception when an error occurs, see the wiki page for more info., :id => 1, :priority => "urgent") # doesn't actually send a request, must explicitly call #save!

ZendeskAPI::Ticket.create!(client, :subject => "Test Ticket", :comment => { :value => "This is a test" }, :submitter_id =>, :priority => "urgent")
ZendeskAPI::Ticket.find!(client, :id => 1)
ZendeskAPI::Ticket.destroy!(client, :id => 1)

Another way is to use the instance methods under client.!(:id => 1) => "Test Ticket")!(:subject => "Test Ticket", :comment => { :value => "This is a test" }, :submitter_id =>, :priority => "urgent")!(:id => 1)

The methods under ZendeskAPI::Client (such as .tickets) return an instance of ZendeskAPI::Collection a lazy-loaded list of that resource. Actual requests may not be sent until an explicit ZendeskAPI::Collection#fetch!, ZendeskAPI::Collection#to_a!, or an applicable methods such as #each.


Resource updating is implemented by sending only the changed? attributes to the server (see ZendeskAPI::TrackChanges). Unfortunately, this module only hooks into Hash meaning any changes to an Array not resulting in a new instance will not be tracked and sent.

zendesk_api_client_rb $ bundle console
> a = => []).tap(&:clear_changes)
> a.changed?(:test)
 => false
> a.test << "hello"
 => ["hello"]
> a.changed?(:test)
 => false
> a.test += %w{hi}
 => ["hello", "hi"]
> a.changed?(:test)
 => true


ZendeskAPI::Collections can be paginated:

tickets =
next_page = # => 3
tickets.fetch! # GET /api/v2/tickets?page=3&per_page=3
previous_page = tickets.prev # => 2
tickets.fetch! # GET /api/v2/tickets?page=2&per_page=3

Iteration over all resources and pages is handled by Collection#all! do |resource|
  # every resource, from all pages, will be yielded to this block

If given a block with two arguments, the page number is also passed in.! do |resource, page_number|
  # all resources will be yielded along with the page number


Callbacks can be added to the ZendeskAPI::Client instance and will be called (with the response env) after all response middleware on a successful request.

client.insert_callback do |env|
  puts env[:response_headers]

Resource management

Individual resources can be created, modified, saved, and destroyed.

ticket =[0] # ZendeskAPI::Ticket.find(client, :id => 1)
ticket.priority = "urgent"
ticket.attributes # => { "priority" => "urgent" }! # Will PUT => true
ticket.destroy! # => true, { :priority => "urgent" })
ticket.new_record? # => true! # Will POST


Warning: this is an experimental feature. Abuse it and lose it.

To facilitate a smaller number of requests and easier manipulation of associated data we allow "side-loading", or inclusion, of selected resources.

For example: A ZendeskAPI::Ticket is associated with ZendeskAPI::User through the requester_id field. API requests for that ticket return a structure similar to this:

"ticket": {
  "id": 1,
  "url": "http.....",
  "requester_id": 7,

Calling ZendeskAPI::Ticket#requester automatically fetches and loads the user referenced above (/api/v2/users/7). Using side-loading, however, the user can be partially loaded in the same request as the ticket.

tickets =
# Or => :users)
# Does *NOT* make a request to the server since it is already loaded
tickets.first.requester # => #<ZendeskAPI::User id=...>


ticket =!(:id => 1, :include => :users)
ticket.requester # => #<ZendeskAPI::User id=...>

Currently, this feature is limited to only a few resources and their associations. They are documented on


Searching is done through the client. Returned is an instance of ZendeskAPI::Collection: => "my search query") # /api/v2/search.json?query=... => "my new query")  # /api/v2/users/search.json?query=...

Special case: Custom resources paths

API endpoints such as tickets/recent or topics/show_many can be accessed through chaining. They will too return an instance of ZendeskAPI::Collection.
client.topics.show_many(:verb => :post, :ids => [1, 2, 3])

Special Case: Current user

Use either of the following to obtain the current user instance:

client.users.find!(:id => 'me')

Special Case: Importing a ticket

Bulk importing tickets allows you to move large amounts of data into Zendesk.

ticket = ZendeskAPI::Ticket.import(client, :subject => "Help", :comments => [{ :author_id => 19, :value => "This is a comment" }])

Attaching files

Files can be attached to ticket comments using either a path or the File class and will be automatically uploaded and attached.

ticket =, :comment => { :value => "attachments" })
ticket.comment.uploads << "img.jpg"
ticket.comment.uploads <<"img.jpg")!

Apps API

v1.1.0 introduces support for the Zendesk Apps API

Creating Apps

upload = client.apps.uploads.create!(:file => "path/to/")
client.apps.create!(:name => "test", :upload_id =>

# Or

app =, :name => "test")
app.upload = "path/to/"!

# Or

upload =, :file => "path/to/")!

app =, :name => "test")
app.upload_id =!

# Or

client.apps.create!(:name => "test", :upload => "")

Note: job statuses are currently not supported, so you must manually poll the job status API for app creation.

body = {}
until %w{failed completed}.include?(body["status"])
  response = client.connection.get(app.response.headers["Location"])
  body = response.body


Updating Apps

upload = client.apps.uploads.create!(:file => "")

# Then

client.apps.update!(:id => 123, :upload_id =>

# Or

app =, :id => 123)
app.upload_id =!

# Or

ZendeskAPI::App.update!(client, :id => 123, :upload_id =>

Deleting Apps

client.apps.destroy!(:id => 123)

app =, :id => 123)

ZendeskAPI::App.destroy!(client, :id => 123)

Installing an App

Installation name is required

installation =, :app_id => 123, :settings => { :name => 'Name' })!

# or

client.apps.installations.create!(:app_id => 123, :settings => { :name => 'Name' })

# or

ZendeskAPI::AppInstallation.create!(client, :app_id => 123, :settings => { :name => 'Name' })

List Installations

apps =

Update Installation!(:id => 123, :settings => { :title => "My New Name" })

installation =, :id => 123)
installation.settings = { :title => "My New Name" }!

ZendeskAPI::AppInstallation.update!(client, :id => 123, :settings => { :title => "My New Name" })

Delete Installation!(:id => 123)

installation =, :id => 123)

ZendeskAPI::AppInstallation.destroy!(client, :id => 123)

Note on Patches/Pull Requests

  1. Fork the project.
  2. Make your feature addition or bug fix.
  3. Add tests for it. This is important so I don't break it in a future version unintentionally.
  4. Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  5. Send me a pull request. Bonus points for topic branches.

Supported Ruby Versions

Tested with Ruby 1.9, 2.0, 2.1, 2.2 and jRuby. Build Status Gem Version Code Climate

Copyright and license

Copyright 2015 Zendesk

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.