The API

The ServiceNowClient

class pysnc.ServiceNowClient(instance, auth, proxy=None, verify=None, cert=None, auto_retry=True)[source]

ServiceNow Python Client

Parameters:
  • instance (str) – The instance to connect to e.g. https://dev00000.service-now.com or dev000000

  • auth – Username password combination (name,pass) or pysnc.ServiceNowOAuth2 or requests.sessions.Session or requests.auth.AuthBase object

  • proxy – HTTP(s) proxy to use as a str 'http://proxy:8080 or dict {'http':'http://proxy:8080'}

  • verify (bool) – Verify the SSL/TLS certificate OR the certificate to use. Useful if you’re using a self-signed HTTPS proxy.

  • cert – if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Attachment(table) Attachment[source]

Create an Attachment object for the current client

Returns:

pysnc.Attachment

GlideRecord(table, batch_size=100, rewindable=True) GlideRecord[source]

Create a pysnc.GlideRecord for a given table against the current client

Parameters:
  • table (str) – The table name e.g. problem

  • batch_size (int) – Batch size (items returned per HTTP request). Default is 100.

  • rewindable (bool) – If we can rewind the record. Default is True. If False then we cannot rewind the record, which means as an Iterable this object will be ‘spent’ after iteration. This is normally the default behavior expected for a python Iterable, but not a GlideRecord. When False less memory will be consumed, as each previous record will be collected.

Returns:

pysnc.GlideRecord

static guess_is_sys_id(value) bool[source]

Attempt to guess if this is a probable sys_id

Parameters:

value (str) – the value to check

Returns:

If this is probably a sys_id

Return type:

bool

property instance: str

The instance we’re associated with.

Returns:

Instance URI

Return type:

str

property session
Returns:

The requests session

GlideRecord

class pysnc.GlideRecord(client: ServiceNowClient, table: str, batch_size: int = 500, rewindable: bool = True)[source]

The GlideRecord object. Normally instantiated via convenience method pysnc.ServiceNowClient.GlideRecord(). This object allows us to interact with a specific table via the table rest api.

Parameters:
  • client (ServiceNowClient) – We need to know which instance we’re connecting to

  • table (str) – The table are we going to access

  • batch_size (int) – Batch size (items returned per HTTP request). Default is 500.

  • rewindable (bool) – If we can rewind the record. Default is True. If False then we cannot rewind the record, which means as an Iterable this object will be ‘spent’ after iteration. This is normally the default behavior expected for a python Iterable, but not a GlideRecord. When False less memory will be consumed, as each previous record will be collected.

add_active_query() QueryCondition[source]

Equivilant to the following:

add_query('active', 'true')
add_encoded_query(encoded_query)[source]

Adds a raw query. Appends (comes after) all other defined queries e.g. add_query()

Parameters:

encoded_query (str) – The same as sysparm_query

add_join_query(join_table, primary_field=None, join_table_field=None) JoinQuery[source]

Do a join query:

gr = client.GlideRecord('sys_user')
join_query = gr.add_join_query('sys_user_group', join_table_field='manager')
join_query.add_query('active','true')
gr.query()
Parameters:
  • join_table (str) – The table to join against

  • primary_field (str) – The current table field to use for the join. Default is sys_id

  • join_table_field (str) – The join_Table field to use for the join

Returns:

query.JoinQuery

add_not_null_query(field) QueryCondition[source]

If the specified field is not empty Equivilant to the following:

add_query(field, '', 'ISNOTEMPTY')
Parameters:

field (str) – The field to validate

add_null_query(field) QueryCondition[source]

If the specified field is empty Equivilant to the following:

add_query(field, '', 'ISEMPTY')
Parameters:

field (str) – The field to validate

add_query(name, value, second_value=None) QueryCondition[source]

Add a query to a record. For example:

add_query('active', 'true')

Which will create the query active=true. If we specify the second_value:

add_query('name', 'LIKE', 'test')

Which will create the query nameLIKEtest

Parameters:
  • name (str) – Table field name

  • value (str) –

    Either the value in which name must be = to else an operator if second_value is specified

    Numbers:

    * =
    * !=
    * >
    * >=
    * <
    * <=
    

    Strings:

    * =
    * !=
    * IN
    * NOT IN
    * STARTSWITH
    * ENDSWITH
    * CONTAINS
    * DOES NOT CONTAIN
    * INSTANCEOF
    

  • second_value (str) – optional, if specified then value is expected to be an operator

add_rl_query(related_table, related_field, operator_condition, stop_at_relationship=False)[source]

Generates a ‘Related List Query’ which is defined as:

RLQUERY<other_table_name>.<field>,<operator><value>[,m2m][^subquery]^ENDRLQUERY

For example, when querying sys_user to simulate a LEFT OUTER JOIN to find active users with no manager:

RLQUERYsys_user.manager,=0^active=true^ENDRLQUERY

If we find users with a specific role:

RLQUERYsys_user_has_role.user,>0^role=ROLESYSID^ENDRLQUERY

But if we want to dotwalk the role (aka set stop_at_relationship=True):

RLQUERYsys_user_has_role.user,>0,m2m^role.name=admin^ENDRLQUERY

Parameters:
  • related_table (str) – The table with the relationship – the other table

  • related_field (str) – The field to use to relate from the other table to the table we are querying on

  • operator_condition (str) – The operator to use to relate the two tables, as in =0 or >=1 – this is not validated by pysnc

  • stop_at_relationship (bool) – if we have a subquery (a query condition ON the RLQUERY) AND it dot walks, this must be True. Default is False.

property batch_size: int
Returns:

The number of records to query in a single HTTP GET

changes() bool[source]

Determines weather any of the fields in the record have changed

delete() bool[source]

Delete the current record

Returns:

True on success

Raise:
AuthenticationException:

If we do not have rights

DeleteException:

For any other failure reason

delete_multiple() bool[source]

Deletes the current query, funny enough this is the same as iterating and deleting each record since we’re using the REST api.

Returns:

True on success

Raise:
AuthenticationException:

If we do not have rights

DeleteException:

For any other failure reason

property fields: List[str] | None
Returns:

Fields in which this record will query OR has queried

get(name, value=None) bool[source]

Get a single record, accepting two values. If one value is passed, assumed to be sys_id. If two values are passed in, the first value is the column name to be used. Can return multiple records.

Parameters:
  • value – the sys_id or the field to query

  • value2 – the field value

Returns:

True or False based on success

get_attachments() Attachment[source]

Get the attachments for the current record or the current table

Returns:

A list of attachments

Return type:

pysnc.Attachment

get_display_value(field) Any[source]

Return the display value for the given field

Parameters:

field (str) – The field, required

Returns:

The field value or None

get_element(field) GlideElement[source]

Return the backing GlideElement for the given field. This is the only method to directly access this element.gr2.serialize()

Parameters:

field (str) – The Field

Returns:

The GlideElement class or None

get_encoded_query() str[source]

Generate the encoded query. Does not respect limits.

Returns:

The encoded query, empty string if none exists

Generate a full URL to the current record. sys_id will be -1 if there is no current record.

Parameters:
  • no_stack (bool) – Default False, adds &sysparm_stack=<table>_list.do?sysparm_query=active=true to the URL

  • list (bool) – Default False, if True then provide a link to the record set, not the current record

Returns:

The full URL to the current record

Return type:

str

Generate a full URL to for the current query.

Returns:

The full URL to the record query

get_row_count() int[source]

Glide compatable method.

Returns:

the total

get_unique_name() str[source]

always give us the sys_id

get_value(field) Any[source]

Return the value field for the given field

Parameters:

field (str) – The field

Returns:

The field value or None

has_next() bool[source]

Do we have a next record in the iteration?

Returns:

True or False

initialize()[source]

Must be called for records to initialize data frame. Will not be able to set values otherwise.

insert() GlideElement | None[source]

Insert a new record.

Returns:

The sys_id of the record created or None

Raise:
AuthenticationException:

If we do not have rights

InsertException:

For any other failure reason

is_new_record() bool[source]

Is this a new record? :return: True or False

property limit: int | None
Returns:

Query number limit

property location: int

Current location within the iteration :return: location is -1 if iteration has not started :rtype: int

next(_recursive=False) bool[source]

Returns the next record in the record set

Returns:

True or False based on success

order_by(column: str)[source]

Set the order in ascending

Parameters:

column – Column to sort by

order_by_desc(column: str)[source]

Set the order in decending

Parameters:

column – Column to sort by

pop_record() GlideRecord[source]

Pop the current record into a new GlideRecord object - equivalent to a clone of a singular record FIXME: this, by the name, should be a destructive operation, but it is not.

Returns:

Give us a new GlideRecord containing only the current record

query(query=None)[source]

Query the table - executes a GET

Raise:
AuthenticationException:

If we do not have rights

RequestException:

If the transaction is canceled due to execution time

rewind()[source]

Rewinds the record (iterable) so it may be iterated upon again. Only possible when the record is rewindable.

serialize(display_value=False, fields=None, fmt=None, changes_only=False, exclude_reference_link=True) Any[source]

Turn current record into a dictGlideRecord(None, ‘incident’)

Parameters:
  • display_valueTrue, False, or 'both'

  • fields (list) – Fields to serialize. Defaults to all fields.

  • fmt (str) – None or pandas. Defaults to None

  • changes_only – Do we want to serialize only the fields we’ve modified?

  • exclude_reference_link – Do we want to exclude the reference link? default is True

Returns:

dict representation

serialize_all(display_value=False, fields=None, fmt=None, exclude_reference_link=True) list[source]

Serialize the entire query. See serialize() docs for details on parameters

Parameters:
  • display_value

  • fields

  • fmt

Returns:

list

set_display_value(field, value)[source]

Set the display value for a field.

Parameters:
  • field (str) – The field

  • value – The Value

Set the link for a field, it is however preferable to to gr.field.set_link(value).

Parameters:
  • field (str) – The field

  • value – The Value

set_new_guid_value(value)[source]

This does make an assumption the guid is a sys_id, if it is not, set the value directly.

Parameters:

value – A 32 byte string that is the value

set_value(field, value)[source]

Set the value for a field.

Parameters:
  • field (str) – The field

  • value – The Value

property table: str
Returns:

The table we are operating on

to_pandas(columns=None, mode='smart')[source]

This is similar to serialize_all, but we by default include a table column and split into __value/__display if the values are different (mode == smart). Other modes include both, value, and display in which behavior follows their name.

` df = pd.DataFrame(gr.to_pandas()) `

Note: it is highly recommended you first restrict the number of columns generated by settings fields() first.

Parameters:

mode – How do we want to serialize the data, options are smart, both, value, display

Return type:

tuple

Returns:

(list, list) inwhich (data, fields)

update() GlideElement | None[source]

Update the current record.

Returns:

The sys_id on success or None

Raise:
AuthenticationException:

If we do not have rights

UpdateException:

For any other failure reason

update_multiple(custom_handler=None) bool[source]

Updates multiple records at once. A custom_handler of the form def handle(response: requests.Response | None) can be passed in, which may be useful if you wish to handle errors in a specific way. Note that if a custom_handler is used this method will always return True

Returns:

True on success, False if any records failed. If custom_handler is specified, always returns True

property view
Returns:

The current view

class pysnc.GlideElement(name, value, *args, **kwargs)[source]

Object backing the value/display values of a given record entry.

capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

changes() bool[source]
Returns:

if we have changed this value

Return type:

bool

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

date_numeric_value() int[source]

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT for a duration field

date_value() datetime[source]

Returns the current as a UTC datetime or throws if it cannot

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

get_display_value() Any[source]

get the display value of the field, if it has one, else just the value

get the link of a field, if it has one, else None

get_name() str[source]

get the name of the field

get_value() Any[source]

get the value of the field

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

nil() bool[source]

returns True if the value is None or zero length

Returns:

if this value is anything

Return type:

bool

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

serialize() dict[source]

Returns a dict with the value,`display_value`, link keys

set_date_numeric_value(ms: int) None[source]

Sets the value of a date/time element to the specified number of milliseconds since January 1, 1970 00:00:00 GMT.

When called, setDateNumericValue() automatically creates the necessary GlideDateTime/GlideDate/GlideDuration object, and then sets the element to the specified value.

set_display_value(value: Any)[source]

set the display value for the field – generally speaking does not have any affect upstream (to the server)

set the reference link for the field – generally speaking does not have any affect upstream (to the server)

set_value(value)[source]

set the value for the field. Will also set the display_value to None

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

Attachment

class pysnc.Attachment(client, table)[source]
add_query(name, value, second_value=None) QueryCondition[source]

Add a query to a record. For example:

add_query('active', 'true')

Which will create the query active=true. If we specify the second_value:

add_query('name', 'LIKE', 'test')

Which will create the query nameLIKEtest

Parameters:
  • name (str) – Table field name

  • value (str) –

    Either the value in which name must be = to else an operator if second_value is specified

    Numbers:

    * =
    * !=
    * >
    * >=
    * <
    * <=
    

    Strings:

    * =
    * !=
    * IN
    * NOT IN
    * STARTSWITH
    * ENDSWITH
    * CONTAINS
    * DOES NOT CONTAIN
    * INSTANCEOF
    

  • second_value (str) – optional, if specified then value is expected to be an operator

as_temp_file(chunk_size: int = 512) SpooledTemporaryFile[source]

Return the attachment as a TempFile

Parameters:

chunk_size – bytes to read in at a time from the HTTP stream

Returns:

SpooledTemporaryFile

get(sys_id: str) bool[source]

Get a single record, accepting two values. If one value is passed, assumed to be sys_id. If two values are passed in, the first value is the column name to be used. Can return multiple records.

Parameters:

sys_id – the id of the attachment

Returns:

True or False based on success

next(_recursive=False)[source]

Returns the next record in the record set

Returns:

True or False based on success

query()[source]

Query the table

Returns:

void

Raise:
AuthenticationException:

If we do not have rights

RequestException:

If the transaction is canceled due to execution time

read() bytes[source]

Read the entire attachment :return: b’’

readlines(encoding='UTF-8', delimiter='\n') List[str][source]

Read the attachment, as text, decoding by default as UTF-8, splitting by the delimiter. :param encoding: encoding to use, defaults to UTF-8 :param delimiter: what to split by, defualt

Returns:

list

write_to(path, chunk_size=512) Path[source]

Write the attachment to the given path - if the path is a directory the file_name will be used

APIs

These are ‘internal’ but you may as well know about them

class pysnc.API(client)[source]
property session
class pysnc.TableAPI(client)[source]
delete(record: GlideRecord) Response[source]
get(record: GlideRecord, sys_id: str) Response[source]
list(record: GlideRecord) Response[source]
patch(record: GlideRecord) Response[source]
post(record: GlideRecord) Response[source]
put(record: GlideRecord) Response[source]
property session
class pysnc.AttachmentAPI(client)[source]
API_VERSION = 'v1'
delete(sys_id)[source]
get(sys_id=None)[source]
get_file(sys_id, stream=True)[source]

This may be dangerous, as stream is true and if not fully read could leave open handles One should always with api.get_file(sys_id) as f:

list(attachment: Attachment)[source]
property session
upload_file(file_name, table_name, table_sys_id, file, content_type=None, encryption_context=None)[source]
class pysnc.BatchAPI(client)[source]
API_VERSION = 'v1'
delete(record: GlideRecord, hook: Callable)[source]
execute(attempt=0)[source]
get(record: GlideRecord, sys_id: str, hook: Callable) None[source]
list(record: GlideRecord, hook: Callable)[source]
patch(record: GlideRecord, hook: Callable) None[source]
post(record: GlideRecord, hook: Callable)[source]
put(record: GlideRecord, hook: Callable) None[source]
property session

Exceptions

exception pysnc.exceptions.AclQueryException[source]
exception pysnc.exceptions.AuthenticationException[source]
exception pysnc.exceptions.DeleteException(message, status_code=None)[source]
exception pysnc.exceptions.EvaluationException[source]
exception pysnc.exceptions.InsertException(message, status_code=None)[source]
exception pysnc.exceptions.InstanceException[source]
exception pysnc.exceptions.NoRecordException[source]
exception pysnc.exceptions.NotFoundException[source]
exception pysnc.exceptions.RequestException[source]
exception pysnc.exceptions.RestException(message, status_code=None)[source]
exception pysnc.exceptions.RoleException[source]
exception pysnc.exceptions.UpdateException(message, status_code=None)[source]
exception pysnc.exceptions.UploadException[source]