• Stars
    star
    387
  • Rank 110,971 (Top 3 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created almost 13 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Official Ruby Zendesk API Client

Zendesk API Client

Test Gem Version Code Climate

Documentation

This Ruby gem is a generic wrapper around Zendesk's REST API. Follow this README and the wiki for how to use it.

You can interact with all the resources defined in resources.rb. Basically we have some cleaver code to convert Ruby objects into HTTP requests.

Please refer to our API documentation for the specific endpoints and once you understand the mapping between Ruby and the HTTP endpoints you should be able to call any endpoint.

The Yard generated documentation is available in at RubyDoc.

Please report any bug in the Github issues page.

You might want to try out this gem in a REPL for exploring your options, if so, check out this project.

Product Support

This Ruby gem supports the REST API's for Zendesk Support, Zendesk Guide, and Zendesk Talk. It does not yet support other Zendesk products such as Zendesk Chat, Zendesk Explore, and Zendesk Sell.

Installation

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

Rubygems

gem install zendesk_api

Bundler

Add it to your Gemfile

gem "zendesk_api"

Then bundle as usual.

Configuration

Configuration is done through a block returning an instance of ZendeskAPI::Client.

require 'zendesk_api'

client = ZendeskAPI::Client.new do |config|
  # Mandatory:

  config.url = "<- your-zendesk-url ->" # e.g. https://yoursubdomain.zendesk.com/api/v2

  # Basic / Token Authentication
  config.username = "[email protected]"

  # 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

  # Raise error when hitting the rate limit.
  # This is ignored and always set to false when `retry` is enabled.
  # Disabled by default.
  config.raise_error_when_rate_limited = false

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

  # Disable resource cache (this is enabled by default)
  config.use_resource_cache = false

  # Changes Faraday adapter
  # config.adapter = :patron

  # Merged with the default client options hash
  # config.client_options = {:ssl => {:verify => false}, :request => {:timeout => 30}}

  # When getting the error 'hostname does not match the server certificate'
  # use the API at https://yoursubdomain.zendesk.com/api/v2

  # Change retry configuration (this is disabled by default)
  config.retry_on_exception = true

  # Error codes when the request will be automatically retried. Defaults to 429, 503
  config.retry_codes = [ 429 ]
end

Usage

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.

ZendeskAPI::Ticket.new(client, :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 => client.current_user.id, :priority => "urgent")
ZendeskAPI::Ticket.find!(client, :id => 1)
ZendeskAPI::Ticket.destroy!(client, :id => 1)

You can also update ticket objects.

ticket = ZendeskAPI::Ticket.find!(client, :id => 1)
ticket.update(:comment => { :value => "This is a test reply." })

ticket.save!

Another way is to use the instance methods under client.

client.tickets.first
client.tickets.find!(:id => 1)
client.tickets.build(:subject => "Test Ticket")
client.tickets.create!(:subject => "Test Ticket", :comment => { :value => "This is a test" }, :submitter_id => client.current_user.id, :priority => "urgent")
client.tickets.destroy!(: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.

Caveats

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 = ZendeskAPI::Trackie.new(:test => []).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

Pagination

ZendeskAPI::Collections can be paginated:

# Note that CBP (cursor based pagination) is the default and preferred way
# and has fewer limitations on deep pagination
tickets = client.tickets.per_page(3)
page1 = tickets.fetch! # GET /api/v2/tickets?page[after]={cursor}&page[size]=3
page2 = tickets.next # GET /api/v2/tickets?page[after]={cursor}&page[size]=3
# ...

# OR...
# Note that OBP (offset based pagination) can incur to various limitations
tickets = client.tickets.page(2).per_page(3)

next_page = tickets.next # => 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:

client.tickets.all! do |resource|
  # every resource, from all pages, will be yielded to this block
end

If given a block with two arguments, the page number is also passed in.

client.tickets.all! do |resource, page_number|
  # all resources will be yielded along with the page number
end

Cursor Based Pagination

A few endpoints related to organizations, tickets, triggers and groups will now make use of cursor based pagination by default. It is also recommended to use CBP whenever the Zendesk developer documentation says it's supported. Pass page[size]=number in the parameters to attempt a CBP request, like the example below:

client.connection.get('/api/v2/suspended_tickets', page: { size: 100 }).body
{"suspended_tickets"=>[...], "meta"=>{"has_more"=>true, "after_cursor"=>" ... ", "before_cursor"=>nil}, "links"=>{"prev"=>nil, "next"=>"..."}}

Callbacks

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]
end

Resource management

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

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

ZendeskAPI::Ticket.new(client, { priority: "urgent" })
ticket.new_record? # => true
ticket.save! # Will POST

Side-loading

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 = client.tickets.include(:users)
# Or client.tickets(:include => :users)
# Does *NOT* make a request to the server since it is already loaded
tickets.first.requester # => #<ZendeskAPI::User id=...>

# OR

ticket = client.tickets.find!(: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 developer.zendesk.com.

Search

Searching is done through the client. Returned is an instance of ZendeskAPI::Collection:

client.search(:query => "my search query") # /api/v2/search.json?query=...
client.users.search(: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.tickets.recent
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')
client.current_user

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" }])

Further documentation can be found on developer.zendesk.com

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 = ZendeskAPI::Ticket.new(client, :comment => { :value => "attachments" })
ticket.comment.uploads << "img.jpg"
ticket.comment.uploads << File.new("img.jpg")
ticket.save!

Apps API

v1.1.0 introduces support for the Zendesk Apps API

Creating Apps

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

# Or

app = ZendeskAPI::App.new(client, :name => "test")
app.upload = "path/to/app.zip"
app.save!

# Or

upload = ZendeskAPI::App::Upload.new(client, :file => "path/to/app.zip")
upload.save!

app = ZendeskAPI::App.new(client, :name => "test")
app.upload_id = upload.id
app.save!

# Or

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

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

  sleep(body["retry_in"])
end

Updating Apps

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

# Then

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

# Or

app = ZendeskAPI::App.new(client, :id => 123)
app.upload_id = upload.id
app.save!

# Or

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

Deleting Apps

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

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

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

Installing an App

Installation name is required

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

# 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 = client.app.installations
apps.fetch!

Update Installation

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

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

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

Delete Installation

client.app.installations.destroy!(:id => 123)

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

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

Running the gem locally

See .github/workflows/main.yml to understand the CI process.

bundle exec rake # Runs the tests
bundle exec rubocop # Runs the lint (use `--fix` for autocorrect)

Releasing a new gem version

  1. From updated master: git checkout -b bump-vX.X.X, according to SemVer
  2. Ensure the CHANGELOG is correct and updated, this is your last opportunity
  3. Execute bundle exec bump patch --tag # minor|major, this bumps the version in a new commit, and adds the relative git tag
  4. Push to GitHub git push origin vX.X.X -u && git push --tags
  5. Raise a PR (example) including the code diff (example)
  6. Get it approved and merged
  7. Post a message in Slack #rest-api (example TODO), so advocacy are aware that we are going to release a new gem, just in case any customer complains about something related to the gem
  8. After 2 hours from the above message, you can approve the release of the gem

Contributing

  1. Fork the project.
  2. Make your feature addition or bug fix.
  3. Add tests for it. This is important so that we don't break it in a future version unintentionally.
  4. Commit. Do not alter Rakefile, version, or history. (If you want to have your own version, that is fine, but bump version in a commit by itself that we can ignore when we pull.)
  5. Submit a pull request.

Note: Live specs will likely fail for external contributors. The Zendesk devs can help with that. If you have permissions and some live specs unexpectedly fail, that might be a data error, see the REPL for that.

Merging contributors pull requests

External contributions don't run live specs, so we need to use a workaround. Assuming a PR from author:author/branch to default_branch:

  1. Create a branch in our repo author_branch
  2. Change the destination branch of the PR to author_branch
  3. Merge
  4. Create a pr in our repo from default_branch
    • Make sure they know the commits still carry their name
    • Example

Copyright and license

Copyright 2015-2023 Zendesk

See LICENSE.

More Repositories

1

android-floating-action-button

Floating Action Button for Android based on Material Design specification
Java
6,374
star
2

maxwell

Maxwell's daemon, a mysql-to-json kafka producer
Java
3,989
star
3

cross-storage

Cross domain local storage, with permissions
JavaScript
2,190
star
4

samson

Web interface for deployments, with plugin architecture and kubernetes support
Ruby
1,446
star
5

ruby-kafka

A Ruby client library for Apache Kafka
Ruby
1,269
star
6

helm-secrets

DEPRECATED A helm plugin that help manage secrets with Git workflow and store them anywhere
Shell
1,159
star
7

curly

The Curly template language allows separating your logic from the structure of your HTML templates.
Ruby
594
star
8

biz

Time calculations using business hours.
Ruby
488
star
9

racecar

Racecar: a simple framework for Kafka consumers in Ruby
Ruby
486
star
10

dropbox-api

Dropbox API Ruby Client
Ruby
362
star
11

zendesk_api_client_php

Official Zendesk API v2 client library for PHP
PHP
335
star
12

stronger_parameters

Type checking and type casting of parameters for Action Pack
Ruby
297
star
13

active_record_shards

Support for sharded databases and replicas for ActiveRecord
Ruby
250
star
14

delivery_boy

A simple way to publish messages to Kafka from Ruby applications
Ruby
238
star
15

android-db-commons

Some common utilities for ContentProvider/ContentResolver/Cursor and other db-related android stuff
Java
223
star
16

radar

High level API and backend for writing web apps that use push messaging
JavaScript
221
star
17

sunshine-conversations-web

The Smooch Web SDK will add live web messaging to your website or web app.
212
star
18

demo_apps

HTML
179
star
19

arturo

Feature Sliders for Rails
Ruby
174
star
20

belvedere

An image picker library for Android
Java
146
star
21

zendesk_jwt_sso_examples

Examples using JWT for Zendesk SSO
Ruby
142
star
22

sunshine-conversations-ios

Smooch
Objective-C
122
star
23

laika

Log, test, intercept and modify Apollo Client's operations
TypeScript
122
star
24

prop

Puts a cork in their requests
Ruby
117
star
25

zendesk_sdk_ios

Zendesk Mobile SDK for iOS
Objective-C
117
star
26

zopim-chat-web-sdk-sample-app

Zendesk Chat Web SDK sample app developed using React
JavaScript
98
star
27

copenhagen_theme

The default theme for Zendesk Guide
Handlebars
98
star
28

app_scaffold

A scaffold for developers to build ZAF v2 apps
JavaScript
90
star
29

node-publisher

A zero-configuration release automation tool for Node packages inspired by create-react-app and Travis CI.
JavaScript
75
star
30

zendesk_apps_tools

Ruby
74
star
31

zendesk_app_framework_sdk

The Zendesk App Framework (ZAF) SDK is a JavaScript library that simplifies cross-frame communication between iframed apps and the Zendesk App Framework
JavaScript
72
star
32

ios_sdk_demo_apps

This repository contains sample iOS code and applications which use our SDKs
Swift
64
star
33

zendesk_sdk_chat_ios

Mobile Chat SDK for iOS
Objective-C
63
star
34

kamcaptcha

A captcha plugin for Rails
Ruby
63
star
35

zcli

A command-line tool for Zendesk
TypeScript
62
star
36

linksf

A mobile website to connect those in need in to services that can help them
JavaScript
62
star
37

sdk_demo_app_android

This is Remember The Date, an Android demo app for our Mobile SDK. All docs available on developer.zendesk.com
Java
61
star
38

property_sets

A way to store attributes in a side table.
Ruby
51
star
39

go-httpclerk

A simple HTTP request/response logger for Go supporting multiple formatters.
Go
51
star
40

android-schema-utils

Android library for simplifying database schema and migrations management.
Java
48
star
41

android_sdk_demo_apps

This repository contains sample android code and applications which use our SDKs
Java
46
star
42

statsd-logger

StatsD + Datadog APM logging server for development - standalone or embedded
Go
44
star
43

sunshine-conversations-android

Smooch Android SDK
42
star
44

support_sdk_ios

Zendesk Support SDK for iOS
Objective-C
37
star
45

react-native-sunshine-conversations

React Native wrapper for Smooch.io
Java
36
star
46

docker-logs-tail

Docker Logs Tail simultaneously tails logs for all running Docker containers, interleaving them in the command line output
JavaScript
35
star
47

call_center

Ruby
34
star
48

curlybars

Handlebars.js compatible templating library in Ruby
Ruby
34
star
49

kasket

A caching layer for ActiveRecord. Puts a cap on your queries!
Ruby
33
star
50

ruby_memprofiler_pprof

Experimental memory profiler for Ruby that emits pprof files.
C
33
star
51

method_struct

Ruby
33
star
52

samlr

Clean room implementation of SAML for Ruby
Ruby
31
star
53

sdk_demo_app_ios

This is Remember The Date, an iOS demo app for our Mobile SDK. All docs available on developer.zendesk.com
Objective-C
31
star
54

volunteer_portal

An event calendar focused on tracking and reporting volunteering opportunities
JavaScript
29
star
55

classic_asp_jwt

A JWT implementation in Classic ASP
ASP
29
star
56

basecrm-ruby

Base CRM API Client
Ruby
29
star
57

ultragrep

the grep that greps the hardest.
C
28
star
58

chariot-tooltips

A javascript library for creating on screen step by step tutorials.
JavaScript
26
star
59

clj-headlights

Clojure on Beam
Clojure
26
star
60

sunshine-conversations-javascript

Javascript API for Sunshine Conversations
JavaScript
26
star
61

android-autoprovider

Utility for creating ContentProviders without boilerplate and with heavy customization options.
Java
25
star
62

basecrm-php

Base CRM API client, PHP edition
PHP
24
star
63

migration_tools

Rake tasks for Rails that add groups to migrations
Ruby
23
star
64

large_object_store

Store large objects in memcache or others by slicing them.
Ruby
22
star
65

term-check

A GitHub app which runs checks for flagged terminology in GitHub repos
Go
22
star
66

basecrm-python

BaseCRM API Client for Python
Python
22
star
67

sdk_unity_plugin

This repository contains a unity plugin which wraps the Zendesk support SDKs
Objective-C
22
star
68

jazon

Test assertions on JSONs have never been easier
Java
21
star
69

ipcluster

Node.js master/worker clustering module for sticky session load balancing using IPTABLES
JavaScript
21
star
70

sunshine-conversations-python

Smooch API Library for Python
Python
21
star
71

cloudwatch-logger

Connects standard input to Amazon CloudWatch Logs
Go
20
star
72

forger

Android library for populating the ContentProvider with test data.
Java
19
star
73

radar_client

High level API and backend for writing web apps that use push messaging
JavaScript
19
star
74

double_doc

Write documentation with your code, to keep them in sync, ideal for public API docs.
Ruby
18
star
75

pakkr

Python pipeline utility library
Python
18
star
76

chat_sdk_ios

Zendesk Chat SDK
Objective-C
18
star
77

goship

Utility that helps find, connect and copy to particular cloud resources using configured providers
Go
18
star
78

url_builder_app

A Zendesk App to help you generate links for agents.
JavaScript
18
star
79

sunshine-conversations-api-quickstart-example

Sample code to get started with the Smooch REST APIs
JavaScript
17
star
80

sunshine-conversations-desk

A sample business system built with Meteor and the Smooch API
CSS
17
star
81

apt-s3

apt method for private S3 buckets
Go
17
star
82

api_client

HTTP API Client Builder
Ruby
16
star
83

zendesk_apps_support

Ruby
16
star
84

iron_bank

An opinionated Ruby interface to the Zuora REST API
Ruby
15
star
85

private_gem

Keeps your private gems private
Ruby
15
star
86

active_record_host_pool

Connect to multiple databases using one ActiveRecord connection
Ruby
15
star
87

sdk_messaging_ios

The Zendesk Messaging SDK
Objective-C
14
star
88

rate_my_app_ios

An open source version of the Rate My App feature from 1.x versions of the Support SDK.
Swift
14
star
89

input_sanitizer

A gem to sanitize hash of incoming data
Ruby
14
star
90

sunshine-conversations-conversation-extension-examples

A series of examples using Smooch conversation extensions
HTML
14
star
91

scala-flow

A lightweight library intended to make developing Google DataFlow jobs in Scala easier.
Scala
14
star
92

punchabunch

Punchabunch: A highly concurrent, easily configurable SSH local-forwarding proxy
Go
14
star
93

zendesk-jira-plugin

Java
13
star
94

sunshine-conversations-ruby

Smooch API Library for Ruby
Ruby
13
star
95

samson_secret_puller

kubernetes sidecar and app to publish secrets to a containerized app.
Ruby
13
star
96

sqlitemaster

Android library for getting existing db schema information from sqlite_master table.
Java
13
star
97

sunshine-conversations-wordpress

PHP
13
star
98

predictive_load

Ruby
12
star
99

sunshine-conversations-api-spec

Sunshine Conversations OpenAPI Specification for v2+
12
star
100

zombie_record

A soft-delete library
Ruby
12
star