REST2#

Python interface to Request Tracker API

Description of Request Tracker REST API: https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html

class rt.rest2.Attachment(file_name: str, file_type: str, file_content: bytes)[source]#

Dataclass representing an attachment.

__init__(file_name: str, file_type: str, file_content: bytes) None#
file_content: bytes#
file_name: str#
file_type: str#
multipart_form_element() Tuple[str, bytes, str][source]#

Convert to a tuple as required for multipart-form-data submission.

to_dict() Dict[str, str][source]#

Convert to a dictionary for submitting to the REST API.

class rt.rest2.Rt(url: str, proxy: Optional[str] = None, verify_cert: Optional[Union[str, bool]] = True, http_auth: Optional[requests.auth.AuthBase] = None, token: Optional[str] = None, http_timeout: Optional[int] = 20)[source]#

API for Request Tracker according to https://docs.bestpractical.com/rt/5.0.2/RT/REST2.html. Interface is based on REST architecture, which is based on HTTP/1.1 protocol. This module is therefore mainly sending and parsing special HTTP messages.

Warning

You need at least version 5.0.2 of RT.

Note

Use only ASCII LF as newline (\\n). Time is returned in UTC. All strings returned are encoded in UTF-8 and the same is expected as input for string values.

__init__(url: str, proxy: Optional[str] = None, verify_cert: Optional[Union[str, bool]] = True, http_auth: Optional[requests.auth.AuthBase] = None, token: Optional[str] = None, http_timeout: Optional[int] = 20) None[source]#

API initialization.

Parameters
  • url – Base URL for Request Tracker API. E.g.: http://tracker.example.com/REST/2.0/

  • proxy – Proxy server (string with http://user:password@host/ syntax)

  • http_auth – Specify a http authentication instance, e.g. HTTPBasicAuth(), HTTPDigestAuth(), etc. to be used for authenticating to RT

  • token – Optional authentication token to be used instead of basic authentication.

  • http_timeout – HTTP timeout after which a request is aborted.

Raises

ValueError – If the specified url is invalid.

comment(ticket_id: Union[str, int], content: str = '', content_type: Literal['text/plain', 'text/html'] = 'text/plain', attachments: Optional[Sequence[rt.rest2.Attachment]] = None) bool[source]#

Adds comment to the given ticket.

Parameters
  • ticket_id – ID of ticket to which comment belongs

  • content – Content of comment

  • content_type – Content type of comment, default to text/plain

  • attachments – Optional list of Attachment objects

Returns

True

Operation was successful

False

Sending failed (status code != 200)

Raises
create_queue(name: str, **kwargs: Any) int[source]#

Create queue.

Parameters
  • name – Queue name (required)

  • kwargs – Optional fields to set (see edit_queue)

Returns

ID of new queue or False when create fails

Raises
create_ticket(queue: str, content_type: Literal['text/plain', 'text/html'] = 'text/plain', subject: Optional[str] = None, content: Optional[str] = None, attachments: Optional[Sequence[rt.rest2.Attachment]] = None, **kwargs: Any) int[source]#

Create new ticket and set given parameters.

Example of message sent to http://tracker.example.com/REST/2.0/ticket/new:

{ "Queue": "General",
  "Subject": "Ticket created through REST API",
  "Owner": "Nobody",
  "Requestor": "somebody@example.com",
  "Cc": "user2@example.com",
  "CustomRoles": {"My Role": "staff1@example.com"},
  "Content": "Lorem Ipsum",
  "CustomFields": {"Severity": "Low"}
}
Parameters
  • queue – Queue where to create ticket

  • content_type – Content-type of the Content parameter; can be either text/plain or text/html.

  • subject – Optional subject for the ticket.

  • content – Optional content of the ticket. Must be specified unless attachments are specified.

  • attachments – Optional list of Attachment objects

  • kwargs

    Other arguments possible to set:

    Requestors, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due

Returns

ID of new ticket

Raises

ValueError – If the content_type is not of a supported format.

create_user(user_name: str, email_address: str, **kwargs: Any) str[source]#

Create user.

Parameters
  • user_name – Username (login for privileged, required)

  • email_address – Email address (required)

  • kwargs – Optional fields to set (see edit_user)

Returns

ID of new user or False when create fails

Raises
delete_queue(queue_id: Union[str, int]) None[source]#

Disable a queue.

Parameters

queue_id – Identification of queue by name (str) or ID (int)

Returns

ID or name of edited queue or False when edit fails

Raises
delete_ticket(ticket_id: Union[str, int]) None[source]#

Mark a ticket as deleted.

Parameters

ticket_id – ID of ticket

Raises
delete_user(user_id: Union[str, int]) None[source]#

Disable a user.

Parameters

user_id – Identification of a user by name (str) or ID (int)

Raises

Creates or deletes a link between the specified tickets.

Parameters
  • ticket_id – ID of ticket to edit

  • link_name – Name of link to edit (‘Parent’, ‘Child’, ‘RefersTo’, ‘ReferredToBy’, ‘DependsOn’, ‘DependedOnBy’)

  • link_value – Either ticker ID or external link.

  • delete – if True the link is deleted instead of created

Returns

True

Operation was successful

False

Ticket with given ID does not exist or link to delete is not found

Raises

InvalidUseError – When none or more than one link is specified. Also, when a wrong link name is used or when trying to link to a deleted ticket.

edit_queue(queue_id: Union[str, int], **kwargs: Any) List[str][source]#

Edit queue.

Parameters
  • queue_id – Identification of queue by name (str) or ID (int)

  • kwargs

    Other fields to edit from the following list:

    • Name

    • Description

    • CorrespondAddress

    • CommentAddress

    • Disabled

    • SLADisabled

    • Lifecycle

    • SortOrder

Returns

List of status messages

Raises
edit_ticket(ticket_id: Union[str, int], **kwargs: Any) bool[source]#

Edit ticket values.

Parameters
  • ticket_id – ID of ticket to edit

  • kwargs

    Other arguments possible to set:

    Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,… (according to RT fields)

    Custom fields can be specified as dict:

    CustomFields = {“Severity”: “Low”}

Returns

True

Operation was successful

False

Ticket with given ID does not exist or unknown parameter was set (in this case all other valid fields are changed)

edit_user(user_id: Union[str, int], **kwargs: Any) List[str][source]#

Edit user profile.

Parameters
  • user_id – Identification of user by username (str) or user ID (int)

  • kwargs

    Other fields to edit from the following list:

    • Name

    • Password

    • EmailAddress

    • RealName

    • NickName

    • Gecos

    • Organization

    • Address1

    • Address2

    • City

    • State

    • Zip

    • Country

    • HomePhone

    • WorkPhone

    • MobilePhone

    • PagerPhone

    • ContactInfo

    • Comments

    • Signature

    • Lang

    • EmailEncoding

    • WebEncoding

    • ExternalContactInfoId

    • ContactInfoSystem

    • ExternalAuthId

    • AuthSystem

    • Privileged

    • Disabled

Returns

List of status messages

Raises
get_all_queues(include_disabled: bool = False) List[Dict[str, Any]][source]#

Return a list of all queues.

Example of a return result:

[
    {
        "InitialPriority": "",
        "_url": "http://localhost:8080/REST/2.0/queue/1",
        "type": "queue",
        "Name": "General",
        "DefaultDueIn": "",
        "Description": "The default queue",
        "CorrespondAddress": "",
        "CommentAddress": "",
        "id": "1",
        "FinalPriority": ""
    }
]
Parameters

include_disabled – Set to True to also return disabled queues.

Returns

Returns a list of dictionaries containing basic information on all queues.

Raises

UnexpectedMessageFormatError – In case that returned status code is not 200

get_attachment(attachment_id: Union[str, int]) Optional[dict][source]#

Get attachment.

Parameters

attachment_id – ID of attachment to fetch

Returns

Attachment as dictionary with these keys:

  • Transaction

  • ContentType

  • Parent

  • Creator

  • Created

  • Filename

  • Content (base64 encoded string)

  • Headers

  • MessageId

  • ContentEncoding

  • id

  • Subject

All these fields are strings, just ‘Headers’ holds another dictionary with attachment headers as strings e.g.:

  • Delivered-To

  • From

  • Return-Path

  • Content-Length

  • To

  • X-Seznam-User

  • X-QM-Mark

  • Domainkey-Signature

  • RT-Message-ID

  • X-RT-Incoming-Encryption

  • X-Original-To

  • Message-ID

  • X-Spam-Status

  • In-Reply-To

  • Date

  • Received

  • X-Country

  • X-Spam-Checker-Version

  • X-Abuse

  • MIME-Version

  • Content-Type

  • Subject

Set of headers available depends on mailservers sending emails not on Request Tracker!

Raises
get_attachments(ticket_id: Union[str, int]) Sequence[Dict[str, str]][source]#

Get attachment list for a given ticket

Example of a return result:

[
    {
        "id": "17",
        "Filename": "README.rst",
        "ContentLength": "3578",
        "type": "attachment",
        "ContentType": "test/plain",
        "_url": "http://localhost:8080/REST/2.0/attachment/17"
    }
]
Parameters

ticket_id – ID of ticket

Returns

List of tuples for attachments belonging to given ticket. Tuple format: (id, name, content_type, size) Returns None if ticket does not exist.

get_attachments_ids(ticket_id: Union[str, int]) Optional[List[int]][source]#

Get IDs of attachments for given ticket.

Parameters

ticket_id – ID of ticket

Returns

List of IDs (type int) of attachments belonging to given ticket. Returns None if ticket does not exist.

Gets the ticket links for a single ticket.

Example of a return result:

[
    {
        "id": "13",
        "type": "ticket",
        "_url": "http://localhost:8080/REST/2.0/ticket/13",
        "ref": "depends-on"
    }
]
Parameters

ticket_id – ticket ID

Returns

Links as lists of strings in dictionary with these keys (just those which are defined):

  • depends-on

  • depended-on-by

  • parent

  • child

  • refers-to

  • referred-to-by

None is returned if ticket does not exist.

Raises

UnexpectedMessageFormatError – In case that returned status code is not 200

get_queue(queue_id: Union[str, int]) Optional[Dict[str, Any]][source]#

Get queue details.

Example of a return result:

{
    "LastUpdatedBy": {
        "_url": "http://localhost:8080/REST/2.0/user/RT_System",
        "type": "user",
        "id": "RT_System"
    },
    "LastUpdated": "2022-03-06T04:53:38Z",
    "AdminCc": [],
    "SortOrder": "0",
    "CorrespondAddress": "",
    "Creator": {
        "id": "RT_System",
        "_url": "http://localhost:8080/REST/2.0/user/RT_System",
        "type": "user"
    },
    "Lifecycle": "default",
    "Cc": [],
    "Created": "2022-03-06T04:53:38Z",
    "_hyperlinks": [
        {
            "_url": "http://localhost:8080/REST/2.0/queue/1",
            "type": "queue",
            "id": 1,
            "ref": "self"
        },
        {
            "ref": "history",
            "_url": "http://localhost:8080/REST/2.0/queue/1/history"
        },
        {
            "ref": "create",
            "type": "ticket",
            "_url": "http://localhost:8080/REST/2.0/ticket?Queue=1"
        }
    ],
    "SLADisabled": "1",
    "Name": "General",
    "TicketCustomFields": [],
    "Disabled": "0",
    "TicketTransactionCustomFields": [],
    "CustomFields": [],
    "Description": "The default queue",
    "CommentAddress": "",
    "id": 1
}
Parameters

queue_id – Identification of queue by name (str) or queue ID (int)

Returns

Queue details as a dictionary

Raises
get_ticket(ticket_id: Union[str, int]) dict[source]#

Fetch ticket by its ID.

Parameters

ticket_id – ID of demanded ticket

Returns

Dictionary with key, value pairs for ticket with ticket_id or None if ticket does not exist. List of keys:

  • id

  • numerical_id

  • Queue

  • Owner

  • Creator

  • Subject

  • Status

  • Priority

  • InitialPriority

  • FinalPriority

  • Requestors

  • Cc

  • AdminCc

  • Created

  • Starts

  • Started

  • Due

  • Resolved

  • Told

  • TimeEstimated

  • TimeWorked

  • TimeLeft

Raises
get_ticket_history(ticket_id: Union[str, int]) Optional[List[Dict[str, Any]]][source]#

Get set of short history items

Parameters

ticket_id – ID of ticket

Returns

List of history items ordered increasingly by time of event. Each history item is a tuple containing (id, Description). Returns None if ticket does not exist.

get_transaction(transaction_id: Union[str, int]) Dict[str, Any][source]#

Get a transaction

Parameters

transaction_id – ID of transaction

Returns

Return a single transaction.

get_user(user_id: Union[int, str]) Dict[str, Any][source]#

Get user details.

Parameters

user_id – Identification of user by username (str) or user ID (int)

Returns

User details as strings in dictionary with these keys for RT users:

  • Lang

  • RealName

  • Privileged

  • Disabled

  • Gecos

  • EmailAddress

  • Password

  • id

  • Name

Or these keys for external users (e.g. Requestors) replying to email from RT:

  • RealName

  • Disabled

  • EmailAddress

  • Password

  • id

  • Name

Raises
last_updated(since: str, queue: Optional[str] = None) Iterator[dict][source]#

Obtains tickets changed after given date.

Parameters
  • since – Date as string in form ‘2011-02-24’

  • queue – Queue where to search

Returns

Iterator of tickets with LastUpdated parameter later than since ordered in decreasing order by LastUpdated. Each ticket is a dictionary, the same as in get_ticket().

Raises

InvalidUseError – If the specified date is of an unsupported format.

merge_ticket(ticket_id: Union[str, int], into_id: Union[str, int]) bool[source]#

Merge ticket into another.

Parameters
  • ticket_id – ID of ticket to be merged

  • into_id – ID of destination ticket

Returns

True

Operation was successful

False

Either origin or destination ticket does not exist or user does not have ModifyTicket permission.

Raises

UnexpectedResponseError – If the response from RT is not as expected

new_correspondence(queue: Optional[Union[str, object]] = None) Iterator[dict][source]#

Obtains tickets changed by other users than the system one.

Parameters

queue – Queue where to search

Returns

Iterator of tickets which were last updated by another user than the system one, ordered in decreasing order by LastUpdated. Each ticket is dictionary, the same as in get_ticket().

reply(ticket_id: Union[str, int], content: str = '', content_type: Literal['text/plain', 'text/html'] = 'text/plain', attachments: Optional[Sequence[rt.rest2.Attachment]] = None) bool[source]#

Sends email message to the contacts in Requestors field of given ticket with subject as is set in Subject field.

Parameters
  • ticket_id – ID of ticket to which message belongs

  • content – Content of email message (text/plain or text/html)

  • content_type – Content type of email message, default to text/plain

  • attachments – Optional list of Attachment objects

Returns

True

Operation was successful

False

Sending failed (status code != 200)

Raises
search(queue: Optional[Union[str, object]] = None, order: Optional[str] = None, raw_query: Optional[str] = None, query_format: str = 'l', **kwargs: Any) Iterator[dict][source]#

Search arbitrary needles in given fields and queue.

Example:

>>> tracker = Rt('http://tracker.example.com/REST/2.0/', 'rt-username', 'top-secret')
>>> tickets = list(tracker.search(CF_Domain='example.com', Subject__like='warning'))
>>> tickets = list(tracker.search(queue='General', order='Status', raw_query="id='1'+OR+id='2'+OR+id='3'"))
Parameters
  • queue – Queue where to search. If you wish to search across all of your queues, pass the ALL_QUEUES object as the argument.

  • order – Name of field sorting result list, for descending order put - before the field name. E.g. -Created will put the newest tickets at the beginning

  • raw_query – A raw query to provide to RT if you know what you are doing. You may still pass Queue and order kwargs, so use these instead of including them in the raw query. You can refer to the RT query builder. If passing raw_query, all other **kwargs will be ignored.

  • query_format

    Format of the query:

    • i: only id fields are populated

    • s: only id and subject fields are populated

    • l: multi-line format, all fields are populated

  • kwargs

    Other arguments possible to set if not passing raw_query:

    Requestors, Subject, Cc, AdminCc, Owner, Status, Priority, InitialPriority, FinalPriority, TimeEstimated, Starts, Due, Text,… (according to RT fields)

    Custom fields CF.{<CustomFieldName>} could be set with keywords CF_CustomFieldName.

    To alter lookup operators you can append one of the following endings to each keyword:

    __exact for operator = (default) __notexact for operator != __gt for operator > __lt for operator < __like for operator LIKE __notlike for operator NOT LIKE

    Setting values to keywords constrain search result to the tickets satisfying all of them.

Returns

Iterator over matching tickets. Each ticket is the same dictionary as in get_ticket().

Raises

UnexpectedMessageFormatError: Unexpected format of returned message. InvalidQueryError: If raw query is malformed

steal(ticket_id: Union[str, int]) bool[source]#

Steal ticket

Parameters

ticket_id – ID of ticket to be merged

Returns

True

Operation was successful

False

Either the ticket does not exist or user does not have StealTicket permission.

Raises

UnexpectedResponseError – If the response from RT is not as expected

take(ticket_id: Union[str, int]) bool[source]#

Take ticket

Parameters

ticket_id – ID of ticket to be merged

Returns

True

Operation was successful

False

Either the ticket does not exist or user does not have TakeTicket permission.

Raises

UnexpectedResponseError – If the response from RT is not as expected

untake(ticket_id: Union[str, int]) bool[source]#

Untake ticket

Parameters

ticket_id – ID of ticket to be merged

Returns

True

Operation was successful

False

Either the ticket does not exist or user does not own the ticket.

Raises

UnexpectedResponseError – If the response from RT is not as expected

user_exists(user_id: Union[int, str], privileged: bool = True) bool[source]#

Check if a given user_id exists.

Parameters
  • user_id – User ID to lookup.

  • privileged – If set to True, only return True if the user_id was found and is privileged.

Returns

bool: True on success, else False.