API Documentation

This part of the documentation covers all the interfaces of glpilib2. For parts where it depends on external libraries, we provide links to the canonical documentation.

class glpilib2.RequestHandler(host_url, app_token, user_api_token, verify_tls=True)[source]

RequestHandler encapsulates the GLPI API in a handy class.

Parameters:
host_url: str

The URL to the GLPI instance.

app_token: str

The application token.

user_api_token: str

The user api token.

verify_tls: bool, default True

If your glpi server is using TLS with a bad certificate, you will need to set this to false.

Attributes:
response_range

Returns the ResponseRange of the previous API call

session_token

Returns the current session token

Methods

add_items:

Create new items (hardware, software, tickets etc.)

change_active_entity:

Change active entity

change_active_profile:

Change the active profile of the current user

delete_items:

Delete a list of items by id

download_document:

Return a document as bytes

download_user_profile_picture:

Return a profile picture as bytes

get_active_entities:

Return active entities of current logged user

get_active_profile:

Return the active profile of the current user

get_full_session:

Return the current PHP session variable

get_glpi_config:

Return the current GLPI_CONFIG variable

get_item:

Return single item (hardware, software, ticket etc.)

get_many_items:

Return a list of items

get_my_entities:

Return all the entities of the current logged user.

get_my_profiles:

Return all the profiles associated to the current logged user.

get_search_options:

List the search options for an item type

get_sub_items:

Return subitems of an item

init_session:

Tries to log into glpi

kill_session:

Ends the session associated with this RequestHandler

response_range:

Returns the ResponseRange of the previous API call

search_items:

Search items according to some criteria

session_token:

Returns the current session token

update_items:

Update the attributes of several items

upload_document:

Uploads a document to GLPI

Notes

Most methods require an active session to perform. If unsure call init_session() after the instantiation.

host_url, app_token and user_api_token are further described in the README.md.

Examples

>>> handler = RequestHandler('localhost', '123456', '654321')
>>> handler.init_session()
>>> handler.get_my_profiles()
{
    'name': "Super-admin",
    'entities': [
        ...
    ]
}
>>> handler.kill_session()
property response_range

Returns the ResponseRange of the previous API call

Set when methods that return multiple items are called.

property session_token

Returns the current session token

Session token is an identification token used for the current connection to the API.

init_session()[source]

Request a session_token() to be used by the other methods.

kill_session(session_id=None)[source]

Destroy a session identified by a session_token().

Defaults to the current open session.

get_my_profiles()[source]

Return all the profiles associated to the current logged user.

Examples

>>> handler.get_my_profiles()
[
     {
         'id': 1
         'name': "Super-admin",
         'entities': [
                 ...
         ]...
    },...
]
get_active_profile()[source]

Return the current active profile.

Examples

>>> handler.get_active_profile()
{
    'name': "Super-admin",
    'entities': [
        ...
    ]
}
change_active_profile(profile_id)[source]

Change active profile to the one indicated by profile_id.

Use get_my_profiles() to obtain the possible profiles.

Raises:
GLPIError

When the profile can’t be found.

get_my_entities(recursive=False)[source]

Return all the entities of the current logged user.

Also returns entities related to the current active profile.

Examples

>>> handler.get_my_entities()
[
    {
        'id':   71
        'name': "my_entity"
    },
    ...
]
get_active_entities()[source]

Return active entities of current logged user.

Examples

>>> handler.get_active_entities()
{
    'id': 1,
    'active_entity_recursive': true,
    'active_entities': [
        {"id":1},
        {"id":71},...
    ]
}
change_active_entity(entity_id)[source]

Change active entity to entity_id.

Use get_my_entities() method to know that are the viable entities.

Warning

Due to a bug with GLPI 9.5.3 if the API cannot find a valid entity with that id it will just report a “Bad Request”.

get_full_session()[source]

Return the current php’s $_SESSION.

Examples

>>> handler.get_full_session()
{
    'valid_id': ...,
    'glpi_currenttime': ...,
    'glpi_use_mode': ...,
    ...
}
get_glpi_config()[source]

Return the current $CFG_GLPI.

Examples

>>> handler.get_glpi_config()
{
    'languages': ...,
    'glpitables': ...,
    'unicity_types':...,
    ...
}
get_item(item_type, id_, expand_dropdowns=False, get_hateoas=True, get_sha1=False, with_devices=False, with_disks=False, with_softwares=False, with_connections=False, with_networkports=False, with_infocoms=False, with_contracts=False, with_documents=False, with_tickets=False, with_problems=False, with_changes=False, with_notes=False, with_logs=False, add_key_names=None)[source]

Return an instance of item_type identified by id and its associated fields.

Documents and User pictures are retrieved with their respective methods.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

id_int

Unique identifier of the itemtype.

expand_dropdownsbool, default False

Show dropdown name instead of id.

get_hateoasbool, default True

Show relations of the item in a links attribute.

See: https://en.wikipedia.org/wiki/HATEOAS

Can’t be disabled due to a bug in the API.

get_sha1bool, default False

Get a sha1 signature instead of the full answer.

with_devicesbool, default False

Only for [Computer, NetworkEquipment, Peripheral, Phone, Printer], retrieve the associated components.

with_disksbool, default False

Only for Computer, retrieve the associated file-systems.

with_softwaresbool, default False

Only for Computer, retrieve the associated software’s installations.

with_connectionsbool, default False

Only for Computer, retrieve the associated direct connections (like peripherals and printers).

with_networkportsbool, default False

Retrieve all network’s connections and advanced network’s information.

with_infocomsbool, default False

Retrieve financial and administrative information.

with_contractsbool, default False

Retrieve associated contracts.

with_documentsbool, default False

Retrieve associated external documents.

with_ticketsbool, default False

Retrieve associated ITIL tickets.

with_problemsbool, default False

Retrieve associated ITIL problems.

with_changesbool, default False

Retrieve associated ITIL changes.

with_notesbool, default False

Retrieve Notes.

with_logsbool, default False

Retrieve item history.

add_key_namesList[str], default None

Retrieve friendly names of the keys “id” keys. Eg.: [‘id’, ‘entities_id’, ‘groups_id_tech’ …]

Examples

>>> handler.get_item(item_type='Computer',id_=71)
{
    "id": 71,
    "entities_id": "Root Entity",
    "name": "adelaunay-ThinkPad-Edge-E320",
    "serial": "12345",
    ...
}
get_many_items(item_type, expand_dropdowns=False, get_hateoas=True, only_id=False, range_=None, sort_by=None, order=None, filter_by=None, is_deleted=False, add_key_names=None)[source]

Returns a set of items identified by item_type.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

expand_dropdowns: bool, default False

Show dropdown name instead of id.

get_hateoasbool, default True

Show relations of the item in a links attribute.

See: https://en.wikipedia.org/wiki/HATEOAS

Can’t be disabled due to a bug in the API.

only_id: bool, default False

Only id and links are returned.

range_: Tuple(int, int), default (0, 50)

The start and end of the pagination.

sort_by: str, default None

Name of the field to sort by.

order: SortOrder, default SortOrder.Ascending

Sort the results according to the sort order of the sort field.

filter_by: Dict[str, str], default None

Filters to pass on the query.

is_deleted: bool, default False

Return deleted elements.

add_key_names: List[str], default None

Retrieve friendly names of the keys “id” keys. Eg.: [‘id’, ‘entities_id’, ‘groups_id_tech’ …]

Examples

>>> handler.get_many_items(item_type='Computer')
[
    {
        "id": 34,
        "entities_id": "Root Entity",
        "name": "glpi",
        ...
    },...
]
get_sub_items(item_type, item_id, sub_item_type, expand_dropdowns=False, get_hateoas=True, only_id=False, range_=None, sort_by=None, order=None, add_key_names=None)[source]

Return subitems of the sub_item_type for the identified item_id.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

item_id: int

Unique identifier of the parent item_type.

sub_item_type: str

The type of subitems you are trying to retrieve.

expand_dropdowns: bool, default False

Show dropdown name instead of id.

get_hateoasbool, default True

Show relations of the item in a links attribute.

See: https://en.wikipedia.org/wiki/HATEOAS

Can’t be disabled due to a bug in the API.

only_id: bool, default False

Only id and links are returned.

range_: Tuple(int, int), default (0, 50)

The start and end of the pagination.

sort_by: str, default None

Name of the field to sort by.

order: SortOrder, default SortOrder.Ascending

Sort the results according to the sort order of the sort field.

add_key_names: List[str], default None

Retrieve friendly names of the keys “id” keys. Eg.: [‘id’, ‘entities_id’, ‘groups_id_tech’ …]

Examples

>>> handler.get_sub_items(item_type='User', item_id=2, sub_item_type='Logs')
[
    {
        "id": 22117,
        "itemtype": "User",
        ...
    }, ...
]
get_search_options(item_type, raw=False, pretty=False)[source]

List the search options of the provided itemtype.

This method provides the options you need for self.search_items.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

raw: bool, default False

Return searchoption uncleaned (as provided by core).

pretty: bool, default False

Will attempt to return the search option organized in a tree based on uid.

Examples

>>> handler.get_search_items('Computer')
{
    "common": "Characteristics",
     "1": {
         'name': 'Name'
         'table': 'glpi_computers'
         'field': 'name'
         'linkfield': 'name'
         'datatype': 'itemlink'
         'uid': 'Computer.name'
     },...
}
>>> handler.get_search_items('Computer', pretty=True)
{'Computer':
    {'Appliance_Item':
        {'Appliance':
            {'ApplianceType':
                {'name':
                    {'available_searchtypes':
                        ['contains', ...],
                    ...
                    'uid': 'Computer.Appliance_Item.Appliance.ApplianceType.name'
                },...
            },...
        },...
    },...
}
search_items(item_type, filters=None, sort_by_id=None, order=None, range_=None, force_display=None, raw_data=False, with_indexes=False, uid_cols=False, give_items=False)[source]

Search items according to some criteria.

Expose the GLPI searchEngine and combine filters to retrieve a list of elements of the specified item_type.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…[3]

filters: List[Dict[str, Any]], default None

A list of json-like objects the represents the query filters and their their relationships. Every filter object must have at least one link field (if it’s not the first object).

link: str

A logical operator of AND, OR, AND NOT

Filter objects keys are objects that narrow down the query. Their keys are:
field: int

The id of the search_option.

meta: boolean

is this criterion a meta one ?

itemtype: str

For meta=true criterion, define the itemtype to use.

searchtype: str

The comparison operation of the filter. It’s one of, contains[1], equals[2], notequals[2], lessthan, morethan, under, notunder.

value:

The value that the field is compared against.

Sub-filter objects can be seen as a pair of () separating a query its single unique key is:

criteria: List[Dict[str, Any]]

A list of Filter objects

An example of filters parameter can be found in the examples section.

sort_by_id: int, default None

id of the search_option to sort by.

order: SortOrder, default SortOrder.Ascending

Sort the results according to the sort order of the sort field.

range_: Tuple(int, int), default (0, 50)

The start and end of the pagination.

force_display: List[int], default None

If set only the columns listed will be present in the query result.

Note: The API documentation says that some columns will always be displayed, those are {1: id, 2: name, 80: Entity}. However that’s not the observed behaviour. Only {1: id} seems to always be displayed.

raw_data: bool, default False

If set debug information about the query is returned in a rawdata field. The results contain the SQL, the search filters as interpreted by the SearchEngine, columns to retrive and many more attributes.

with_indexes: bool, default False

Instead of the resulting data field being a list of items found, it is a dict with id as key. Ordering cannot work with this argument.

uid_cols: bool, default False

Replaces the numeric id from the resulting data object with human readable names as identified by the uid field returned by get_search_options.

give_items: bool, default False

Returns a HTML link to the item on the portal in the first field for each returned item, inside a ‘data_html’ field in the returned object.

Notes

1. contains will use a wildcard search per default. You can restrict at the beginning using the ^ character, and/or at the end using the $ character.

2. equals and notequals are designed to be used with dropdowns. Do not expect those operators to search for a strictly equal value (see 1. above).

3. You can use ‘AllAssets’ as the item_type to retrieve a combination of all asset’s items, regardless of type.

Examples

>>> handler.search_items("Monitor", range=(0,2))
{
    "totalcount": "2",
    "range": "0:2",
    "data": [
        {
            "searchoptions_id": "value",
            ...
        },...
    ],...
}

With give_items.

>>> handler.search_items("Monitor", give_items=True)
{
            "data": [...],
            "data_html": [
                {
                    "1": "<a id='Monitor_1_1' href='/front/monitor.form.php?id=1'>monitor1</a>",
                    "19": "2021-02-20 21:38",
                    "23": "manufacturer1",
                    ...
                }...
            ],...
        }

The next example demonstrates the usage of fiters with a nested filter.

>>> nested_filter = [
...     {
...         "field":      34,
...         "searchtype": "equals",
...         "value":      1
...     }, {
...         "link":       "OR",
...         "field":      35,
...         "searchtype": "equals",
...         "value":      1
...     }
... ]
>>> filters = [
...     {
...         "link":       "AND',
...         "field":      31,
...         "searchtype": "equals",
...         "value":      1
...      }, {
...         "link":       "AND",
...         "meta":       True,
...         "itemtype":   "User",
...         "field":      1,
...         "searchtype": "equals",
...         "value":      1
...      }, {
...         "link":       "AND",
...         "criteria" : nested_filter
...      }
... ]
>>> handler.search_items("Monitor", force_display=[1], filters=filters)
{
    "totalcount": ...,
    "range": ...,
    "data": [
        {
            "1": "W2242",...
        },...
    ],...
}

The above filter variable is roughly equivalent to the expression.

>>> [m for m in Monitors if (
...        field[31] == 1
...        and User.field[1] == 1
...        and (
...            field[34] == 1
...            or field[35] == 1))]
add_items(item_type, data)[source]

Add one or several items

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

data: Union[Dict, List[Dict]]

A dict with fields of itemtype to be inserted. You can add several items in one action by passing a list of dict instead.

Returns:
Union[Dict, List[Dict]]

In case a single object was passed will return a single dict, otherwise a list of dicts.

In case of success the dicts might contain only the id of the inserted object, otherwise it will contain a message field with the error message.

Notes

So far I’ve been unable to trigger an error with add_items for a single item in a list. add_items fail silently whenever you provide an invalid attribute ex: an attribute that references an object that doesn’t exist, a duplicated id field or even when you try to set a field that doesn’t exist.

Examples

>>> handler.add_items("Software", {"name": "my software", "location": 1})
{'id': 4, 'message': 'Item Successfully Added: item name'}

For several objects.

>>> handler.add_items(
... "Software",
... [
...     {"name": "second software added", "location": 1},
...     {"name": "third software added", "uuid": "2313"},
... ])
[
    {"id":8, "message": ""},
    {"id":false, "message": "You don't have permission to perform this action."},
    {"id":9, "message": ""}
]
update_items(item_type, data)[source]

Update the attributes of several items.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

data: List[Dict[str, Any]]

A list of dict with fields of item_type to be updated. One of those fields must be id. Field names must be lowercase.

Returns:
List[Dict]

Each field has the form {‘id’: 2, ‘message’: ‘’}

Notes

As with the add_items method, this method is highly permissive and will not return an error if the item with that id doesn’t exist, or the field is incorrect. In fact, it might create new objects in case the id doesn’t exist.

delete_items(item_type, ids, purge=False, log=True)[source]

Delete a list of existing objects.

Parameters:
item_type: str

Type of the item. Eg: ‘Computer’, ‘Ticket’, ‘Software’…

ids: List[int]

List of ids of the objects that will be deleted.

purge: bool, default False

If set the item will skip the trash bin (if applicable), being immediately deleted.

log: bool, default True

If set the deletion operation will be logged.

Returns:
List[Dict]
Returns a list of objects in the form of {‘id’: True, ‘message’: ‘’}
In case of failure the id field value will be false and message will be set.
upload_document(file, name=None, file_name=None)[source]

Uploads a document to GLPI

Parameters:
name: str, default None

The human readable name. If unset it will be the same as file_name.

file: IO

A file like object

file_name: str, default None

If you want the file uploaded to have a name different from the file you can set this variable. Ex: ‘my_filename.png’ If unset it will try to obtain a name from the file to use as the file_name.

download_document(id_)[source]

Return a Document identified by id as bytes

download_user_profile_picture(id_)[source]

Return the profile picture of a User identified by id as bytes

class glpilib2.ResponseRange(start, end, count, max)[source]

Range of a query.

Some API methods produce a response in the header that describe the range of the query. That data is collected and wrapped in this type of object. To obtain it use the response_range() property of RequestHandler.

Attributes:
start: int

The query was retrieved begining on the start number.

end: int

The query was retrieved with no elements after end number.

count: int

Number of items returned.

max: int

Maximum possible number of items for this item type.

class glpilib2.SortOrder(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Handy Enum for ordering queries.

Attributes:
Ascending
Desceding
class glpilib2.GLPIError[source]

Base glpilib2 exception

Attributes:
args
class glpilib2.GLPIRequestError(response, *args)[source]

Request error.

In some circumstances GLPI doesn’t have a specific error message for a method. This exception is raised in those cases with details about how the request was made and the response that was received.

Attributes:
error_code: int

The HTTP response code

error_message: str

The error message returned by the API (might be empty)

request_headers: dict
payload: str | bytes
url: str

The final response URL

method: str

The HTTP method of the request

response: requests.Response

The actual response object is provided for further debugging