- Notifications
You must be signed in to change notification settings - Fork186
Official Ruby Zendesk API Client
License
zendesk/zendesk_api_client_rb
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
This Ruby gem is a generic wrapper around Zendesk's REST API. Follow this README and thewiki for how to use it.
You can interact with all the resources defined inresources.rb
. Basically we have some cleaver code to convert Ruby objects into HTTP requests.
Please refer to ourAPI 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 atRubyDoc.
Please report any bug in theGithub issues page.
You might want to try out this gem in a REPL for exploring your options, if so, check outthis project.
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 asZendesk Chat, Zendesk Explore, and Zendesk Sell.
The Zendesk API client can be installed using Rubygems or Bundler.
gem install zendesk_api
Add it to your Gemfile
gem "zendesk_api"
Thenbundle
as usual.
Configuration is done through a block returning an instance ofZendeskAPI::Client
.
require'zendesk_api'client=ZendeskAPI::Client.newdo |config|# Mandatory:config.url="<- your-zendesk-url ->"# e.g. https://yoursubdomain.zendesk.com/api/v2# Basic / Token Authenticationconfig.username="login.email@zendesk.com"# Choose one of the following depending on your authentication choice# More information on obtaining API tokens can be found here:# https://developer.zendesk.com/api-reference/introduction/security-and-auth/#api-tokenconfig.token="your zendesk token"# OAuth Authentication# More information on obtaining OAuth access tokens can be found here:# https://developer.zendesk.com/api-reference/introduction/security-and-auth/#oauth-access-tokenconfig.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, 503config.retry_codes=[429]end
The result of configuration is an instance ofZendeskAPI::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 thewiki 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.firstclient.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 underZendeskAPI::Client
(such as.tickets
) return an instance ofZendeskAPI::Collection
, a lazy-loaded list of that resource.Actual requests may not be sent until an explicitZendeskAPI::Collection#fetch!
,ZendeskAPI::Collection#to_a!
, or an applicable methods suchas#each
.
Resource updating is implemented by sending only thechanged?
attributes to the server (seeZendeskAPI::TrackChanges
).Unfortunately, this module only hooks intoHash
meaning any changes to anArray
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
ZendeskAPI::Collections
can be paginated:
# Note that CBP (cursor based pagination) is the default and preferred way# and has fewer limitations on deep paginationtickets=client.tickets.per_page(3)page1=tickets.fetch!# GET /api/v2/tickets?page[after]={cursor}&page[size]=3page2=tickets.next# GET /api/v2/tickets?page[after]={cursor}&page[size]=3# ...# OR...# Note that OBP (offset based pagination) can incur to various limitationstickets=client.tickets.page(2).per_page(3)next_page=tickets.next# => 3tickets.fetch!# GET /api/v2/tickets?page=3&per_page=3previous_page=tickets.prev# => 2tickets.fetch!# GET /api/v2/tickets?page=2&per_page=3
Iteration over all resources and pages is handled byCollection#all
:
client.tickets.all!do |resource|# every resource, from all pages, will be yielded to this blockend
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 numberend
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 wheneverthe Zendesk developer documentation says it's supported.Passpage[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 can be added to theZendeskAPI::Client
instance and will be called (with the response env) after all response middleware on a successful request.
client.insert_callbackdo |env|putsenv[:response_headers]end
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 => trueticket.destroy!# => trueZendeskAPI::Ticket.new(client,{priority:"urgent"})ticket.new_record?# => trueticket.save!# Will POST
To facilitate a smaller number of requests and easier manipulation of associated data we allow "side-loading," or inclusion, of selected resources.
For example:AZendeskAPI::Ticket
is associated withZendeskAPI::User
through therequester_id
field.API requests for that ticket return a structure similar to this:
"ticket": {"id":1,"url":"http.....","requester_id":7,...}
CallingZendeskAPI::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 loadedtickets.first.requester# => #<ZendeskAPI::User id=...># ORticket=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 ondeveloper.zendesk.com.
For better control over your data and to avoid large response sizes, consider fetching related resources explicitly. This approach can help you manage data loading more precisely and can lead to optimized performance for complex applications.
ticket=ZendeskAPI::Ticket.find(id:1)requester=ZendeskAPI::User.find(id:ticket.requester_id)
By explicitly fetching associated resources, you can ensure that your application only processes the data it needs, improving overall efficiency.
Support for theAgent Availability API
An agent’s availability includes their state (such as online) for each channel (such as messaging), and their unified state across channels. It also includes the work items assigned to them.
# All agent availabilitiesclient.agent_availabilities.fetch# fetch availability for one agent, their channels and work itemsagent_availability=ZendeskAPI::AgentAvailability.find(client,386390041152)agent_availability.channelsagent_availability.channels.first.work_items# Using the agent availability filterZendeskAPI::AgentAvailability.search(client,{select_channel:'support'})ZendeskAPI::AgentAvailability.search(client,{channel_status:'support:online'})
Searching is done through the client. Returned is an instance ofZendeskAPI::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=...
API endpoints such astickets/recent
ortopics/show_many
can be accessed through chaining.They will too return an instance ofZendeskAPI::Collection
.
client.tickets.recentclient.topics.show_many(:verb=>:post,:ids=>[1,2,3])
Use either of the following to obtain the current user instance:
client.users.find!(:id=>'me')client.current_user
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 ondeveloper.zendesk.com
Files can be attached to ticket comments using either a path or the File class and willbe 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!
v1.1.0 introduces support for the ZendeskApps API
upload=client.apps.uploads.create!(:file=>"path/to/app.zip")client.apps.create!(:name=>"test",:upload_id=>upload.id)# Orapp=ZendeskAPI::App.new(client,:name=>"test")app.upload="path/to/app.zip"app.save!# Orupload=ZendeskAPI::App::Upload.new(client,:file=>"path/to/app.zip")upload.save!app=ZendeskAPI::App.new(client,:name=>"test")app.upload_id=upload.idapp.save!# Orclient.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{failedcompleted}.include?(body["status"])response=client.connection.get(app.response.headers["Location"])body=response.bodysleep(body["retry_in"])end
upload=client.apps.uploads.create!(:file=>"NewApp.zip")# Thenclient.apps.update!(:id=>123,:upload_id=>upload.id)# Orapp=ZendeskAPI::App.new(client,:id=>123)app.upload_id=upload.idapp.save!# OrZendeskAPI::App.update!(client,:id=>123,:upload_id=>upload.id)
client.apps.destroy!(:id=>123)app=ZendeskAPI::App.new(client,:id=>123)app.destroy!ZendeskAPI::App.destroy!(client,:id=>123)
Installation name is required
installation=ZendeskAPI::AppInstallation.new(client,:app_id=>123,:settings=>{:name=>'Name'})installation.save!# orclient.apps.installations.create!(:app_id=>123,:settings=>{:name=>'Name'})# orZendeskAPI::AppInstallation.create!(client,:app_id=>123,:settings=>{:name=>'Name'})
apps=client.app.installationsapps.fetch!
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"})
client.app.installations.destroy!(:id=>123)installation=ZendeskAPI::AppInstallation.new(client,:id=>123)installation.destroy!ZendeskAPI::AppInstallation.destroy!(client,:id=>123)
See.github/workflows/main.yml
to understand the CI process.
bundle exec rake # Runs the testsbundle exec rubocop # Runs the lint (use `--fix` for autocorrect)
A new version is published to RubyGems.org every time a change toversion.rb
is pushed to themain
branch.In short, follow these steps:
- Update
version.rb
, - merge this change into
main
, - post a message in Slack
#rest-api
, 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, - after 2 hours from the above message, you canapprove the release of the gem
- look atthe action for output.
To create a pre-release from a non-main branch:
- change the version in
version.rb
to something like1.2.0.pre.1
or2.0.0.beta.2
, - push this change to your branch,
- go toActions → “Publish to RubyGems.org” on GitHub,
- click the “Run workflow” button,
- pick your branch from a dropdown.
- Fork the project.
- Make your feature addition or bug fix.
- Add tests for it. This is important so that we don't break it in a futureversion unintentionally.
- Commit. Do not alter
Rakefile
, version, or history. (If you want to haveyour own version, that is fine, but bump version in a commit by itself thatwe can ignore when we pull.) - 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.
External contributions don't run live specs, so we need to use a workaround. Assuming a PR fromauthor:author/branch
todefault_branch
:
- Create a branch in our repo
author_branch
- Change the destination branch of the PR to
author_branch
- Merge
- Create a pr in our repo from
default_branch
- Make sure they know the commits still carry their name
- Example
Copyright 2015-2023 Zendesk
SeeLICENSE.
About
Official Ruby Zendesk API Client
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.