REST: Difference between revisions

From Request Tracker Wiki
Jump to navigation Jump to search
 
Line 236: Line 236:


'''orderby'''
'''orderby'''


By this parameter you can change the sort field and order of the search result. To sort a list ascending just put a + before the fieldname, otherwise a -. Eg: -Created (will put the newest tickets at the beginning).
By this parameter you can change the sort field and order of the search result. To sort a list ascending just put a + before the fieldname, otherwise a -. Eg: -Created (will put the newest tickets at the beginning).
Line 242: Line 241:
Example:
Example:
  <code>/REST/1.0/search/ticket?query=Queue='fooQueue'&orderby=+Created</code>
  <code>/REST/1.0/search/ticket?query=Queue='fooQueue'&orderby=+Created</code>


'''format'''
'''format'''

Revision as of 09:46, 17 December 2013

Abstract

The REST Interface gives you access to your RT Database. The complete communication is encapsulated in the HTTP protocol. The interface should be accessible in your installation.

Though you may see references to older 3.x releases of RT below, Best Practical indicates that the REST stuff has not changed in any significant way in 4.x as of, at least, 1/2012.

Interface

Base URL: .../REST/1.0/. The default response should be:

RT/3.4.5 200 Ok
                           
                   # Invalid object specification: 'index.html'
                           
                   id: index.html
                     

Authentication

The REST Interface does not support HTTP-Authentication. So you must get a valid Session-Token and submit the cookie each request. You usually get a Session-Cookie by submitting the default login form. Use variables "user" for login and "pass" for password values. wget doesn't escape any characters in the --post-data option so make sure you properly escape any special characters in the password.

See the wget invocation line below:

wget  --keep-session-cookies \
 --save-cookies cookies.txt \
 --post-data 'user=UUUU&pass=PPPP' \
 http://my.rt.server

You need the -keep-session-cookies option to make wget save session cookies.

Ticket

Ticket Properties

Gets the data for a single ticket, not including the history and comments.

Request: /REST/1.0/ticket/<ticket-id>/show

RT/3.4.5 200 Ok

id: ticket/<ticket-id>
Queue: <...>
Owner: <...>
Creator: <...>
Subject: <...>
Status: <...>
Priority: <...>
InitialPriority: <...>
FinalPriority: <...>
Requestors: <...>
Cc: <...>
AdminCc: <...>
Created: <...>
Starts: <...>
Started: <...>
Due: <...>
Resolved: <...>
Told: <...>
TimeEstimated: <...>
TimeWorked: <...>
TimeLeft: <...>

Ticket Links

Gets the ticket links for a single ticket.

Request: REST/1.0/ticket/<ticket-id>/links/show

RT/3.8.2 200 Ok

id: ticket/<ticket-id>/links
HasMember: fsck.com-rt://your.server.com/ticket/<another-id>
ReferredToBy: fsck.com-rt://your.server.com/ticket/<another-id>
DependedOnBy: fsck.com-rt://your.server.com/ticket/<another-id>
MemberOf: fsck.com-rt://your.server.com/ticket/<another-id>
RefersTo: fsck.com-rt://your.server.com/ticket/<another-id>
DependsOn: fsck.com-rt://your.server.com/ticket/<another-id>

Ticket Attachments

Gets a list of all attachments related to the ticket

Request: /REST/1.0/ticket/<ticket-id>/attachments

Ticket Attachment

Gets the metadata and content of a specific attachment.

Request: /REST/1.0/ticket/<ticket-id>/attachments/<attachment-id>

RT/3.8.0 200 Ok
 
id: <attachment-id>
Subject:
Creator: <user-id>
Created: <timestamp>
Transaction: <transaction-id>
Parent: <parent-id>
MessageId:
Filename: <filename>
ContentType: application/octet-stream
ContentEncoding: none
 
Headers: MIME-Version: 1.0
         X-Mailer: MIME-tools 5.427 (Entity 5.427)
         Content-Type: application/octet-stream;
           name="<filename>"
         Content-Disposition: inline; filename="<filename>"
         Content-Transfer-Encoding: base64
         Content-Length: <length in bytes>

Content: ...
         ...
         ...

NOTE: RT returns the content indented with 9 spaces on each line, so that it lines up with the "Content:" header. Even if you strip this out with a regexp, the content is still UTF-8, which is probably not what you want. To get the original binary data back, strip out the 9 spaces with a regexp, strip off the 3 carriage returns at the end, and then convert the whole thing from UTF-8 to the native character encoding of the attachment, whatever that is. RT doesn't tell you, so you have know. If the attachments were uploaded by a U.S. Windows system, odds are that Windows-1252 is what you want. If you can't get the binary back intact, see the next method below.

Ticket Attachment Content

Gets the attachment data content without additional metadata or whitespace characters

Request: /REST/1.0/ticket/<ticket-id>/attachments/<attachment-id>/content

RT/3.8.0 200 Ok

...
...
...

So to get the original content you still have to strip the first 2 lines of the response.

Ticket History

Gets a list of all the history items for a given ticket.

Request: /REST/1.0/ticket/<ticket-id>/history

RT/3.4.5 200 Ok

# <history-count>/<history-count> (/total)

<history-id>: <history-name>
<history-id>: <history-name>
...

You will get an additional row, for each history entry found. The first entry is usually: "Ticket created by ...".

There are two ways to get history item detail: you can do one of these and then recursively perform ticket/history/id/<history-id> for each history-id from this REST call, but that is extremely wasteful and will scale horribly. What you really want to do is one REST call but get the long format:

Request: /REST/1.0/ticket/<ticket-id>/history?format=l

RT/3.8.2 200 Ok

# <n>/<n> (id/<history-id>/total)

id: <history-id>
Ticket: <ticket-id>
TimeTaken: <...>
Type: <...>
Field: <...>
OldValue: <...>
NewValue: <...>
Data: <...>
Description: <...>
Content: <...>
Creator: <...>

Created: <...>

Attachments:
             <attachment-id>: <filename> (<size>)
             <attachment-id>: <filename> (<size>)

--

# <n>/<n> (id/<history-id>/total)
...

NOTE: the double dash "--" will occur in the long format between each history item. You can split the output on "--" and iterate over it, parsing out the data with an RFC822 parser, such as an email handling library.

Ticket History Entry

Gets the history information for a single history item. Note that the history item must actually correspond to the ticket.

Request: /REST/1.0/ticket/<ticket-id>/history/id/<history-id>

RT/3.4.5 200 Ok

# 70/70 (id/114856/total)

id: <history-id>
Ticket: <ticket-id>
TimeTaken: <...>
Type: <...>
Field: <...>
OldValue: <...>
NewValue: <...>
Data: <...>
Description: <...>

Content: <lin1-0>
         <line-1>
         ...
         <line-n>
         
Creator: <...>
Created: <...>
Attachments: <...>

IMPORTANT NOTE: At least with RT 3.8.0, when you request a history item with this method AND you have attached a file that has Mime type text/plain to the same item (eg. a comment with an attachement), RT will return the complete content of the attachment for the key "Content:" and not your real comment that you can see in the web frontend. This may lead to some problems if the requestor does not expect to get a comment content that is for example 1.8 MB of text. With other Mime type attachments this however seems to work. I don't know if this is a feature or a bug.


Ticket Search

Request: /REST/1.0/search/ticket?query=<query>&orderby=<sort-order>&format=<format>

Parameters

query

You can use any query generated by the query builder - or feel free to write your own. Here an example that will do the following: Find all tickets that have no owner and the status new or open

query= Owner = 'Nobody' AND ( Status = 'new' OR Status = 'open' )

Example: to get all the tickets in "fooQueue" you'd access:

/REST/1.0/search/ticket?query=Queue='fooQueue'

Example: to get the tickets for a custom field "Contact Name" you'd access:

/REST/1.0/search/ticket?query='CF.{Contact Name}'='Shaun Wallace'


orderby

By this parameter you can change the sort field and order of the search result. To sort a list ascending just put a + before the fieldname, otherwise a -. Eg: -Created (will put the newest tickets at the beginning).

Example:

/REST/1.0/search/ticket?query=Queue='fooQueue'&orderby=+Created


format

  • i: ticket/<ticket-id>
  • s: <ticket-id>: <ticket-subject>
  • l: a multi-line format (This action does not work for me (error); Cris: Works for me on 3.8.4)

Example:

/REST/1.0/search/ticket?query=Queue='fooQueue'&orderby=+Created&format=i

Ticket Create

To create a new ticket: post on /REST/1.0/ticket/new with a variable named "content",

containing "key: value" line by line, example:

Testing the new ticket section

id: ticket/new
Queue: <queue name>
Requestor: <requestor email address>
Subject: <subject>
Cc: <...>
AdminCc: <...>
Owner: <...>
Status: <...>
Priority: <...>
InitialPriority: <...>
FinalPriority: <...>
TimeEstimated: <...>
Starts: <...>
Due: <...>
Text: <The ticket content>
CF-<CustomFieldName>: <CustomFieldValue>

If you want to have a multiline Text, prefix every line with a blank.

Due: <...>
Text: This is 
 a 
 multiline Text
 !!!
CF-<CustomFieldName>: <CustomFieldValue>

The response should look like:

RT/4.0.6 200 Ok

# Ticket 775 created.

Ticket Edit

To update an existing ticket: post on /REST/1.0/ticket/<ticket-id>/edit with a variable named "content", containing "key: value" line by line (like the one displayed when issuing ticket/<ticket-id>/show). Example:

Priority: 5
TimeWorked: 15
  • PHP
 
             $username = rt_user;
             $password = rt_pass;
             $url = "http://server.domain.tld/REST/1.0/ticket/<ticket id>/edit?user=$username&pass=$password";
             $request = new HttpRequest($url, HTTP_METH_POST);
             $post_data=array("content"=>"AdminCc: userX\nText: This is a REST test edit ticket\n");
             
             // add the post fields  
             $request->addPostFields($postData);
             // response from RT
             $response = $request->send()->getBody();
             print_r($response);
             

Tickets History Reply

Same as comment: post on /REST/1.0/ticket/<ticket-id>/comment with a variable name content, containing "key: value" line by line:

id: <ticket-id>
Action: correspond
Text: the text comment
Cc: <...>
Bcc: <...>
TimeWorked: <...>
Attachment: an attachment filename/path

Cc and Bcc are for this reply only (I think).

Ticket History Comment

To add a comment to an existing ticket: POST on "/REST/1.0/ticket/<ticket-id>/comment" with a variable name "content", containing "key: value" line by line:

id: <ticket-id>
Action: comment
Text: the text comment
Attachment: an attachment filename/path

Action can be "comment" or "correspond". For a list of fields you can use in correspondence, try "/opt/rt3/bin/rt correspond ticket/1"

If your comment contains multiple lines, each new line must be preceded by a space (e.g. "line 1\n line 2").

If you used "Attachment", you must add to your POST a variable "attachment_1" that contains the raw attachment in multi-part file object.

You can upload more attachments as well, in this case you have to separate the file names in the "Attachment" with "\n "(a newline and space, without quotes) and add a new variable "attachment_$i" to your POST where $i is the index of attachment.

You need to send header to post comments

Ticket Links Edit

To update links on an existing ticket: POST on "/REST/1.0/ticket/<ticket-id>/links" with a variable named "content", containing "key: value" line by line (like the one displayed when issuing "ticket/<ticket-id>/links"). Example:

DependsOn: 54354
RefersTo: http://some.external/link

User Properties

Gets the data for a single user.

Request: /REST/1.0/user/<user-id>

RT/3.8.4 200 Ok

id: user/<user-id>
Name: <...>
Password: ********
EmailAddress: <...>
RealName: <...>
Organization: <...>
Privileged: <...>
Disabled: <...>

Also you can use user login instead of user ID.


User Create

To create a new user: post on /REST/1.0/user/new with a variable named "content", containing "key: value" line by line, like the response to /user/<user-id>

User Edit

To update an existing user: post on /REST/1.0/user/<user-id>/edit with a variable named "content", containing "key: value" line by line (like the one displayed when issuing user/<user-id>/show).



Queue Properties

Gets the data for a single queue.

Request: /REST/1.0/queue/<queue-id>

RT/3.8.4 200 Ok

id: queue/<queue-id>
Name: <...>
Description: <...>
CorrespondAddress: <...>
CommentAddress: <...>
InitialPriority: <...>
FinalPriority: <...>
DefaultDueIn: <...>

Logout

To logout: post on /REST/1.0/logout with empty content.

Types

  • new
  • open
  • stalled
  • resolved
  • rejected
  • deleted

+ other custom values defined in you local RT portal.


History entry type

  • Create
  • CustomField
  • EmailRecord
  • Status
  • CommentEmailRecord
  • Correspond
  • Comment
  • Priority
  • Give
  • Steal
  • Take
  • Untake
  • AddWatcher
  • DeleteWatcher
  • AddLink
  • DeleteLink
  • AddReminder
  • OpenReminder
  • ResolveReminder
  • Set
  • Force
  • Subject
  • Told
  • PurgeTransaction

Miscellaneous

Data format

History entries time returns in UTC, boolean returns as 1 (true) and 0(false). Use only "\n", not "\r\n"in post content. Comments in response body starts with

  1. symbol.

Request status

To get real request/post status you need to check status code in first line of server response.

Examples

Perl

To get the results of a single request (without setting the Session-Cookie) - assuming you've set:

  • $uri to your RT REST URL
  • $access_user to your username
  • $access_password to your password
  • $ticketNumber to the ticket you want to see
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
$ua->agent("YOURUSERAGENTHERE");
 
my $response = $ua->post($uri."ticket/$ticketNumber",
   ['user' => $access_user, 'pass' => $access_password],
    'Content_Type' => 'form-data');

if ($response->is_success) {
   print $response->decoded_content;
}

Java

import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
  
public class RtTicketCreator {
   static final String BASE_URI = "http://rt.xxx.com/REST/1.0";
 
   public static void main(String[] args) throws IOException {
 
      PostMethod mPost = new PostMethod(BASE_URI + "/ticket/new?user=username&pass=password");
      Part[] parts = { new StringPart("content", "Queue: General\nSubject: 123") };
      mPost.setRequestEntity(new MultipartRequestEntity(parts, mPost.getParams()));
      HttpClient cl = new HttpClient();
      cl.executeMethod(mPost);
      System.out.println(mPost.getResponseBodyAsString());
   }
}

Java ( Based on new Apache HttpComponents library )

/*
* RT ticket creator based on the current Apache HttpComponents library 4.1.3
* Created by Koustubha Kale, kmkale at youtility dot in
*/
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class NewApacheHttpcomponentsRtTicketCreator {

    public static void main(String[] args) throws Exception {
        
        DefaultHttpClient httpclient = new DefaultHttpClient();
	try {
            
            HttpPost httppost = new HttpPost("http://rt.xxx.com/rt/REST/1.0" +
                    "/ticket/new?user=username&pass=password");
	    StringBody content = new StringBody("Queue: General\nSubject: 123");
	    MultipartEntity reqEntity = new MultipartEntity();
	    reqEntity.addPart("content", content);
	    httppost.setEntity(reqEntity);
	    System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
        }
    }
    
}

Python

import cookielib
import urllib
import urllib2
       
# creates a cookie for the rtserver with the credentials given at initialization.
# define your credentials here
access_user = 'your_login'
access_password = 'your_password'
       
# here is the RequestTracker URI we try to access
uri = 'http://your-rt-instance.com/REST/1.0/'
       
# trying login on rt server
cj = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)
data = {'user': access_user, 'pass': access_password}
ldata = urllib.urlencode(data)
login = urllib2.Request(uri, ldata)
try:
   response = urllib2.urlopen(login)
   print response.read()
   print "login successful"
except urllib2.URLError:
   # could not connect to server
   print "Not able to login"

Ruby

#!/usr/bin/env ruby
require 'net/http'

user = 'username'
pass = 'password'
uri = URI('https://rt.example.com/REST/1.0/ticket/123/show')

req = Net::HTTP::Post.new(uri.path)
req.set_form_data('user' => user, 'pass' => pass)

res = Net::HTTP.start(uri.hostname, uri.port, 
  :use_ssl => uri.scheme == 'https', 
  :set_debug_output => $stderr) do |http|
  http.request(req)
end

case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
  puts "HTTP response code:  #{res.code}"
  puts "HTTP message: #{res.message}"
  puts "Response:"

  res.each do |key,val|
    puts "#{key} => #{val}"
  end

  puts "Data:"
  puts res.body
else
  res.value
end

PHP

$username = rt_user;
$password = rt_pass;
$url = "http://server.domain.tld/REST/1.0/ticket/<ticket id>/show?user=$username&pass=$password";
$request = new HttpRequest($url, HTTP_METH_GET);
/* if you want's to pass additional parameters */
$request->addQueryData(array());
$response = $request->send();
print_r($response);

OR

$username = rt_user; $password = rt_pass; $url = "http://server.domain.tld/REST/1.0/ticket/new?user=$username&pass=$password"; $request = new HttpRequest($url, HTTP_METH_POST); // Note : to add data in custom fields you need to add element like below example // in $post_data array // Example : \nCF-customfield1:testdata $post_data=array("content"=>"Queue: General\nRequestor: user@domain\nSubject: REST test 1\nOwner: userX\nAdminCc: userX\nText: This is a REST test\n"); $request->addPostFields($post_data); try { response = $request->send()->getBody(); print_r($response); }catch (HttpException $ex) { echo $ex;

}

C#

// Using "WCF REST Starter Kit" (http://msdn.microsoft.com/en-us/netframework/cc950529.aspx)
using (var client = new HttpClient("http://rt.site.com/REST/1.0/"))
{
   client.TransportSettings.Cookies = new CookieContainer();

   var form = new HttpUrlEncodedForm();
   form.Add("user", "LOGIN");
   form.Add("pass", "PASSWORD");

   client.Post(string.Empty, form.CreateHttpContent());

   // 1. Get ticket data
   using (var request = client.Get("ticket/1234/show"))
   {
      string content = request.Content.ReadAsString();
      // Some logic
   }

   // 2. Post ticket reply with attachment
   var formPost = new HttpMultipartMimeForm();
   byte[] attachment = new byte[];
   string content = string.Empty;
         
   // Store data in attachment
   // Store data in content string ("Field: Value" line by line)
   // ...
         
   formPost.Add("content", content);
   formPost.Add("attachment_1", "attachment_1", HttpContent.Create(attachment, "application/octet-stream"));
                             
   using (var post = client.Post("ticket/1234/comment"), formPost.CreateHttpContent()))
      // Some logic
}

Powershell (v3)

  • Escape Powershell reserved chars in user/pass
  • If connecting via SSL, use fqdn of server, not cname
  • Use `n (newline) when composing new ticket structure

Read RT queue based on query:

$servername="Your Servername here"
$u="user=Username"
$p="pass=Password"
$q="search/ticket?query=(Status='open' OR Status='new') AND (Queue='GENERAL' OR Queue='FOO') AND Owner='Nobody'"
$uri="https://" + $servername + "/rt/REST/1.0/" + $q + "&" + $u + "&" + $p
$RT=Invoke-WebRequest -Uri  $uri -SessionVariable sess
$rt.Content


VB.NET

Public Sub AddAttachmentToRT(ByVal url As String, ByVal fileName As String, ByVal filePath As String)

        Dim dataBoundary As String = "--xYzZY"
        Dim request As HttpWebRequest
        Dim fileType As String = "image/jpeg"

        'Create a POST web request to the REST interface using the passed URL
        request = CType(WebRequest.Create(url), HttpWebRequest)
        request.ContentType = "multipart/form-data; boundary=xYzZY"
        request.Method = "POST"
        request.KeepAlive = True

        'Write the request to the requestStream
        Using requestStream As IO.Stream = request.GetRequestStream()

            'Create a variable "attachment_1" in the POST, specify the file name and file type
            Dim preAttachment As String = dataBoundary + vbCrLf _
            + "Content-Disposition: form-data; name=""attachment_1""; filename=""" + fileName + """" + vbCrLf _
            + "Content-Type: " + fileType + vbCrLf _
            + vbCrLf

            'Convert this preAttachment string to bytes
            Dim preAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(preAttachment)

            'Write this preAttachment string to the stream
            requestStream.Write(preAttachmentBytes, 0, preAttachmentBytes.Length)

            'Write the file as bytes to the stream by passing its exact location
            Using fileStream As New IO.FileStream(Server.MapPath(filePath + fileName), IO.FileMode.Open, IO.FileAccess.Read)

                Dim buffer(4096) As Byte
                Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)

                Do While (bytesRead > 0)

                    requestStream.Write(buffer, 0, bytesRead)
                    bytesRead = fileStream.Read(buffer, 0, buffer.Length)

                Loop

            End Using

            'Create a variable named content in the POST, specify the attachment name and comment text
            Dim postAttachment As String = vbCrLf _
            + dataBoundary + vbCrLf _
            + "Content-Disposition: form-data; name=""content""" + vbCrLf _
            + vbCrLf _
            + "Action: comment" + vbLf _
            + "Attachment: " + fileName + vbCrLf _
            + "Text: Whatever You Want" + vbCrLf _
            + vbCrLf _
            + "--xYzZY--"

            'Convert postAttachment string to bytes
            Dim postAttachmentBytes As Byte() = System.Text.Encoding.UTF8.GetBytes(postAttachment)

            'Write the postAttachment string to the stream
            requestStream.Write(postAttachmentBytes, 0, postAttachmentBytes.Length)

        End Using

        Dim response As Net.WebResponse = Nothing

        'Get the response from our REST request to RT
        'Required to capture response, without this Try-Catch attaching will fail
        Try
            response = request.GetResponse()

            Using responseStream As IO.Stream = response.GetResponseStream()

                Using responseReader As New IO.StreamReader(responseStream)

                    Dim responseText = responseReader.ReadToEnd()

                End Using

            End Using

        Catch exception As Net.WebException

            response = exception.Response

            If (response IsNot Nothing) Then

                Using reader As New IO.StreamReader(response.GetResponseStream())

                    Dim responseText = reader.ReadToEnd()

                End Using

                response.Close()

            End If

        Finally

            request = Nothing

        End Try

    End Sub

Convenience libraries

There are libraries which do much of the low-level work shown in the examples below for you, and provide an easier programming interface for dealing with RT:

Perl RT::Client::REST Google Code perl -MCPAN -e install RT::Client::REST
Ruby RT-Client RubyGems gem install rt-client
Ruby Roart GitHub gem install roart
Python rtkit GitHub pip install python-rtkit
Python python-rt GitLab pip install rt
Java RT-REST GitHub N/A
PHP RTPHPLib GitHub N/A