接口服务

介绍

iTop提供了一个REST/JSON接口,允许第三方应用程序与iTop进行远程交互,用来检索、创建或更新iTop对象。该接口基于一组简单的HTTP POST请求。从iTop传递和检索的数据使用UTF-8字符集的JSON编码。

这样的请求可以通过任何能够发出HTTP/POSTs和JSON编码数据的编程语言执行。通过跨站点脚本(iTop支持CORS和JSON-P),请求甚至可以直接在任何web页面内的javascript中运行。REST JSON Playground中给出了一个用javascript编写跨站点脚本的例子。

POST请求的URL像这样:

<itop-root>/webservices/rest.php?version=1.3

这些请求需要传递下列参数:

  • auth_user

  • auth_pwd

  • json_data

实际上,HTTP方法可以是POST或GET(需要JSON-P支持)。出于安全原因(为了避免以明文形式传递凭据),以及GET对输入数据的大小施加了限制,建议使用POST和HTTPS。支持HTTP基本身份验证。

谁可以访问:

从iTop 2.5.0开始,拥有REST Services User角色的用户才能访问REST web服务。

  • 确保使用REST web服务的脚本具有REST Services User角色。

  • 如果没有此REST Services User附加角色,只有管理员角色的用户是无法访问REST的。

如果您想模拟前面的行为(即允许任何用户访问REST web服务),请添加配置参数secure_rest_services并将其设置为false。

根据您测试REST/JSON API的方式,您可能需要在iTop配置文件中设置allowed_login_types中启用url。

参数:

让我们看一下HTTP服务的所有参数:

参数描述默认值
version

API版本。它是一种确保目标iTop服务器可以提供功能的方法,并且确保了脚本的稳定:只要版本是可用的,操作将保持不变,除以下情况:bug修复,返回消息的修改,返回的JSON结构中的新元素。

备注:支持参数:'1.0', '1.1', '1.2', '1.3', '1.4'。详见:core\restservices.class.inc.php中定义

-
auth_user用户登录名-
auth_pwd用户密码-
json_data

包含处理请求所需的所有信息的结构体。特别是,这里给出了请求的操作。

 
callback

使用 JSON-P (带填充的JSON)时,设置。

 

这些参数适用于所请求的任何类型的操作。

操作: list_operations

您应该熟悉的第一个操作是:list_operations。此命令返回所有可能操作的列表。

json_data输入的语法非常简单:

{ "operation": "list_operations" }

回复如下:

{ "version": "1.2", "operations": [ { "verb": "core/create", "description": "Create an object", "extension": "CoreServices" }, { "verb": "core/update", "description": "Update an object", "extension": "CoreServices" }, { "verb": "core/get", "description": "Search for objects", "extension": "CoreServices" } ], "code": 0, "message": "Operations: 3" }

注意这个部分:

{ "code": 0, "message": "Everything went well" }

…对于rest.php提供的所有服务都是通用的,而返回的其他信息取决于请求的操作。

错误代码

错误代码可以在applicationextension.inc.php中找到,作为类RestResult的常量:

常量含义
0OK没有遇到任何问题
1UNAUTHORIZED

缺失/错误的凭据或用户没有足够的权限执行请求操作

2MISSING_VERSION

缺失‘version’参数

3MISSING_JSON

缺失'json_data' 参数

4INVALID_JSON

输入结构不是一个有效的JSON字符串

5MISSING_AUTH_USER

缺失‘auth_user’参数

6MISSING_AUTH_PWD

缺失‘auth_pwd’参数或者你正在使用URL登录方式并且在你的iTop配置文件没有允许URL登录方式

10UNSUPPORTED_VERSION

指定版本没有操作可用

11UNKNOWN_OPERATION

指定版本请求的操作无效

12UNSAFE

因为可能引起数据(完整性)丢失,请求的操作不能执行

100INTERNAL_ERROR

无法执行该操作,请查看有关疑难解答的信息

核心服务

核心服务是一些通用的服务。它们等价于 iTop Core PHP APIs:DBObject, DBObjectSearch 和 DBObjectSet.

使用这些服务,假如你知道足够多的类和它们的属性的话,你能够操作所有种类的数据。

如何指定一个键

一个键可以识别一个对象。此类规范可用于确定操作的目标对象,并用于确定external key(或“foreign key”)的值。

三种允许的格式:

  • 指定对象的id(数值型):

...
   "key": 123
  • 指定一个查询语句 (OQL):

...
   "key": "SELECT UserRequest WHERE caller_name LIKE \"monnet\""
  • 指定查询条件(所有的查询条件通过AND操作符组合):

... "key": { "name": "Monnet", "first_name": "Claude" }

如何指定一个值

给定属性值的格式依赖于属性类型。

下面的列子阐述了这些情况:

"name": "Monnet", "first_name": "Claude", "age": 80, "picture": { "data": "iVBORw0KGgoAAAAN.......AAAAElFTkSuQmCC", "filename": "smiley.png", "mimetype": "image/png" }

标量

对于大多数的属性类型,值简单地是一个标量。

对于外部键,值是一个键(查看上面的定义)。

对于以纯文本格式的文本域,新的一行通过“\”制定。

iTop 2.3开始工单的描述采用HTML格式化。能够修改数据模型,并且返回描述字段到一个纯文本域中,或者你转换数据到HTML格式(返回了转换后的内容到<br>标记,和像 '<' 或 '&'这样的HTML实体)

例:

"name": "Monnet", "description": "A famous french artist.\nLaunched the impressionism trend." "presentation": "<p>A famous french artist</p><p>Launched the <em>impressionism</em> trend.</p>" "age": 80, "org_id": "SELECT Organization WHERE name = 'Demo'", "location_id": 3, "supervisor_id": { "name": "Foo", "first_name": "John" }

斑点

对于Blob(即二进制数据),该值以三个项目的数组形式给出:数据,文件名和mimetype。

  • “数据”是已被base 64编码的二进制数据(请参阅PHP / base64_encode)
  • “文件名”是原始文件的名称。其目的是提供默认文件名,以防进一步下载该文件。
  • “ mimetype”必须与文件格式匹配,以便iTop可以正确显示它。

例:

"picture": { "data": "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVChTfZHRDYMwDESzQ2fqhHx3C3ao+MkW/WlnaFxfzk7sEnE6JHJ+NgaKZN2zLHVN2ssfkae0Da7FQ5PRk/ve4Hcx19Ie6CEGuh/6vMgNhwanHVUNbt73lUDbYJ+6pg8b3+m2RehsVPdMXyvQY+OVkB+Rrv64lUjb3nq+aCA6v4leRqtfaIgimr53atBy9PlfUhoh3fFCNDmErv9FWR6ylBL5AREbmHBnFj5lAAAAAElFTkSuQmCC", "filename": "smiley.png", "mimetype": "image/png" }

案例日志

从iTop 2.3开始,案例日志以HTML格式设置。因此,速记语法希望注释以HTML格式设置。

从iTop 2.0.3开始,填充“ CaseLog”字段可以使用3种语法:速记语法,单个项目或整个日志。

速记语法

如果提供了简单的文本字符串,则该文本将作为具有当前日期和时间以及当前用户的案例日志中的新条目添加,并且该文本将被隐式地视为HTML格式。

例:

"public_log": "blah blah blah",
丰富的语法

如果提供了带有名为add_item的条目的结构,则可以指定其他信息:

  • 用户名称(默认为RESTTJSON API使用的凭据)
  • 条目的日期时间(默认为“现在”)
  • 注释的格式(默认为“ html”,可以设置为“文本”)

例:

"public_log": {
   "add_item":
   {
      "date": "yyyy-mm-dd hh:mm:ss",
      "user_login": "jfoo",
      "message": "The first line\nAnother line",
      "format":"text"
   }
},
完整的语法

如果提供了一个名为``items''的数组,那么案例日志的全部内容将被提供的条目替换。

例:

"public_log":
{
   "items":
   [
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "<p>The first line</p><p>A second line</p>"
      },
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "<p>The first line</p><p>A second line</p>",
         "format": "html"
      },
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "blah blah blah",
         "format": "text"
      }
   ]
},

链接集

对于链接集,价值是对象定义的数组。

例:

"contacts_list":
[
   {
      "role": "artist",
      "contact_id":
      {
         "finalclass": "Person",
         "name": "monet",
         "first_name": "claude"
      }
   },
   {
      "role": "Basket-ball",
      "contact_id": "SELECT Team WHERE name = 'San Antonio Spurs'"
   },
   {
      "contact_id": 1234
   }
]

回复

回复的coree…操作的格式如下:

{ "objects": { "objectclass::objectkey": { ... } }, "code": 0, "message": "Found: 1" }

每个对象是表单:

{ "code": 0, "message": "", "class": "Person", "key": 1234, "fields": { "id": 1234, "name": "My last name", "status": "Active", "org_id": 123, ..... ..... ..... } }

给定的属性列表可以通过参数输出_fields(如果有)的平均值来控制。参数输出_fields可以具有以下形式:

  • 逗号分隔的属性代码列表(例如:“名称,状况,org_id”)。在这里只能给出查询的类的属性。
  • *表示所查询类的所有属性
  • * +(自2.0.3起)表示找到的每个对象的所有属性(子类可能比查询的类具有更多的属性)

运维:核心

搜索对象列表。

例:

Passing the following json_data:

{ "operation": "core/get", "class": "Person", "key": "SELECT Person WHERE email LIKE '%.com'", "output_fields": "friendlyname, email" }

or, using another form of “key”:

{ "operation": "core/get", "class": "Person", "key": 1, "output_fields": "*" }

从2.6.1(公关#25多亏了Dennis Lassiter!),分页使用两个新参数处理:

  • limit(int):要返回的结果数量(默认值:0 =无限制)
  • page(int):要返回的页码(不能<1)

可以使用classsclassspropertiessorder数据模型XML节点来控制记录的排序。

范例:

{ "operation": "core/get", "class": "Person", "key": "SELECT Person", "output_fields": "friendlyname, email" "limit": "5", "page": "2" }

运维:创建

创建给定类的新对象

传递以下json_数据:

{ "operation": "core/create", "comment": "Synchronization from blah...", "class": "UserRequest", "output_fields": "id, friendlyname", "fields": { "org_id": "SELECT Organization WHERE name = \"Demo\"", "caller_id": { "name": "monet", "first_name": "claude", } "title": "Houston, got a problem!", "description": "The fridge is empty" } }

…将导致创建新的用户请求。

一些属性具有特殊格式:

  • 链接集:当前仅支持间接链接集,请参见上面的示例
  • 斑点:文档内容(例如Documenileefile)必须位于表单中。{数据:base64-encoded-数据,mimetype:…,filename:…}
  • 案例日志:允许使用三种形式。
  1. 传递字符串等效于在GUI中添加新消息:代表当前用户(用于调用Web服务的凭据)记录该消息。
  2. 在表单{add_item:{message:'blah',用户_id:123,date:'2012-02-28 10:30'}}中传递结构也添加了一条消息。用户_id和date是可选的,分别默认为当前用户和当前日期和时间。指定用户_id要求用于调用用户的凭据具有管理员权利,否则用户会因未授权用户而失败。
  3. 在表单中传递一个结构{items:[{message:'blah'}]}设置整个日志。

回复的示例:

{ "code": 0, "message": "", "objects": { "UserRequest::123": { "code": 0, "message": "created", "class": "UserRequest", "key": 29, "fields": { "id": 29, "friendlyname": "R-000029" } } } }

运维:核心更新

更新一台对象

传递以下json_数据:

{ "operation": "core/update", "comment": "Synchronization from blah...", "class": "UserRequest", "key": { "description": "The fridge is empty" }, "output_fields": "friendlyname, title, contact_list", "fields": { "contacts_list": [ { "role": "pizza delivery", "contact_id": { "finalclass": "Person", "name": "monet", "first_name": "claude" } } ] } }

…通过将联系人列表设置为一个联系人(克劳德·莫奈)和角色“比萨饼交付”,将更新用户请求(由其描述“冰箱是空的”标识)。

不支持多个(批量)更新。如果密钥规范匹配多个对象,则更新将失败,并带有错误:查询的多个项目(xx)…。

运维:核心刺激

更新一个对象并向变更施加刺激,使状态变为对象

传递以下json_数据:

{ "operation": "core/apply_stimulus", "comment": "Synchronization from blah...", "class": "UserRequest", "key": 15, "stimulus": "ev_assign", "output_fields": "friendlyname, title, status, contact_list", "fields": { "team_id": 18, "agent_id": 57 } }

… will update the User

…将会通过设置处理人员_id和team_id字段(对于所分配的状态是必选的)来更新用户请求(由其键“ 15”标识),然后将刺激ev_分派应用于使工单从新状态到转换的状态。状态分配。

第一个版本不支持多个(批量)apply_stimulus。如果密钥规范匹配多个对象,则更新将失败,并显示错误:查询的多个项目(xx)....

运维:核心元素

删除一组对象

传递以下json_数据:

{ "operation": "core/delete", "comment": "Cleanup for customer Demo", "class": "UserRequest", "key": { "org_id": 2 }, "simulate": false }

…将删除客户#2的用户请求。

删除可能意味着链接到已删除对象的其他对象的删除和更新。报告中列出了所有对象。

使用模拟正确调整脚本

每个报告的对象都有一个删除的状况代码和一条提供其他信息的消息。状况代码在coreerestservices.class.inc.php中定义为RestDelete类的常量:

价值不变含义
0对象已根据初始请求删除
1问题一般问题(用户权利或……?)
2自动删除必须删除以保留数据库集成
3自动删除问题必须删除以保留数据库集成,但这是不可能的
4明确要求必须删除以保留数据库集成,但是必须明确要求
5自动更新必须更新以保留数据库集成
6自动更新问题必须更新以保留数据库集成,但这是不可能的

运维:coreeget_相关

搜索相关对象。

给定对象或对象列表,搜索正在影响那些对象或受这些对象影响的其他对象。

传递以下json_数据:

{ "operation": "core/get_related", "class": "Server", "key": 1, "relation": "impacts", "depth": 4, "redundancy": true, "direction": "down" }

…对于服务器:: 1所做的所有配置项,将搜索用作影响度。搜索的深度限制为4次迭代(默认为20次)。

结果将在表单中:

{ "objects": { "objectclass::objectkey": { ... } }, "relations": { "origin-class::origin-key": [ { "key": "destination-class::destination-key" } ] }, "code": 0, "message": "Scope: 1; Found: Server=4, VirtualMachine=3, Farm=1" }

搜索可以在对象列表上执行。只需将输入参数'key'指定为OQL(例如“ SELECT服务器”),就会考虑与任何服务器相关的所有配置项。在结果摘要中,这就是所谓的“范围”。

运维:coreecheck_证书

检查用户登录名+密码。

Passing the following json_data:

{ "operation": "core/check_credentials", "user": "john", "password": "abc123", }

… will reply (if everything went well)…

{ "code": 0, "message": "", "authorized": true, }

从iTop 2.3.0开始,可以停用账号(通过将其状况设置为“禁用”)。禁用账号时,check_credentials返回已授权:false。

例子和游乐场

如果您已经安装了iTop(版本2.0.1+),则单击这里是测试的REST API.

这是相应的代码: jsfiddle游乐场

如何集成RESTTJSON调用的示例:使用bash和wget

如何添加服务

通过开发声明类(包含在您的自定义模块中)的模块(或扩展)来实现接口iRestServiceProvider,可以扩展服务。

安装模块后,您的自定义服务将可用并通过运维= list_operations列出。

变更记录

优拓版本JSON REST版本变化
2.0.11.0已建立
2.0.21.1在返回的对象信息中添加了“密钥”(在1.0中需要进行一些解析),将对象对象搜索转换为严格的对象(与宽松的对象相对:包含...),允许重置外部密钥(设置为0,表示“搜索”)
2.0.31.2完全处理案例日志(可以完全读取或写入),EnumssGET提供原始价值而不是本地化标签,允许使用HTTP基本身份验证方法,添加了动词coreecheck_credentials,改进了错误报告(缺少身份验证参数,错误的类编写链接集),将选项* +添加到身份验证的对象的所有字段(不仅是查询类的字段),修复了删除对象的报告
2.2.01.3动词get_related:在冗余分析中添加了选项冗余和方向以将冗余纳入账号。由于影响度的原因,现在已禁止用户帐户和安全门户用户一起使用RESTTJSON Web服务。如果仅使用其中一个Web服务来检查用户的凭据,请调整代码以使用coreecheck_credentials操作。由于影响度的原因,现在仅允许对指定的对象类别具有批量读取权限的用户使用coreeget和coreeget_related操作。
2.5.2, 2.6.1, 2.7.01.4动词coreeget:添加了分页参数限制和页面

原帖链接:https://www.itophub.io/wiki/page?id=2_7_0%3Aadvancedtopics%3Arest_json


REST/JSON services

Presentation

iTop provides a REST/JSON interface which allows third party applications to remotely interact with iTop for retrieving, creating or updating iTop objects. This interface is based on a set of simple HTTP POST requests. The data passed to and retrieved from iTop are encoded in JSON using the UTF-8 character set.

Such requests can be performed from any programming language capable os issuing HTTP/POSTs and manipulating JSON encoded data. Requests can even be run directly in javascript inside any web page by the mean of cross-site scripting (iTop supports both CORS and JSON-P). An example of such cross-site scripting in javascript is given in the REST JSON Playground.

The URL to POST the requests looks like:

<itop-root>/webservices/rest.php?version=1.3

Such requests expect the following parameters to be passed:

  • auth_user

  • auth_pwd

  • json_data

In fact, the HTTP method can be either POST or GET (this is needed for JSON-P support). POST and HTTPS are recommended for security reasons (to avoid passing the credentials in clear text) and also because GET imposes a limit on the size of the input data. HTTP Basic authentication is supported.

Who can access it:

Since iTop 2.5.0, the access to the REST web services is restricted to the users having the profile REST Services User.

  • As REST web services can easily be put in a loop, users must have write access and bulk write on the classes they modify. Applying a stimulus is a modification.

  • Make sure that your scripts using REST web services have REST Services User profile.

  • Your users with Administrator profile won't have access to REST without this REST Services User additional profile.

If you want to emulate the previous behavior (i.e. allow any user to access the REST web services) add the configuration parameter secure_rest_services and set it to false.

Depending on how you test REST/JSON API, you may need to enable url within the allowed_login_types set in the Configuration file of your iTop

Parameters: Let's have a look at all the parameters of this HTTP service:

ArgumentDescriptionDefaut value
versionVersion of the API. It is a way to make sure that the targetted iTop server can deliver some functionality, and it ensures stability for your scripts: as long as a version is available, the operations will remain unchanged, with the exception of the following cases: bug fixes, modification in the returned messages, new elements into the returned JSON structure.-
auth_userUser login-
auth_pwdUser password-
json_dataString containing in a structured way all information required to process your request. In particular, the requested operation is given here. 
callbackIf set, then JSON-P (JSON with padding) is used 

These parameters apply to any type of operation that is requested.

Operation: list_operations

The first operation you should be familiar with is: list_operations. This command returns the list of all possible operations.

The syntax of the json_data input is as simplest as could be:

{ "operation": "list_operations" }

The reply will look like:

{ "version": "1.2", "operations": [ { "verb": "core/create", "description": "Create an object", "extension": "CoreServices" }, { "verb": "core/update", "description": "Update an object", "extension": "CoreServices" }, { "verb": "core/get", "description": "Search for objects", "extension": "CoreServices" } ], "code": 0, "message": "Operations: 3" }

Note that the part:

{ "code": 0, "message": "Everything went well" }

…is common to all the services delivered by rest.php, the other information returned depends on the requested operation.

Error codes

The error codes are available in applicationextension.inc.php, as constants of the class RestResult:

ValueConstantMeaning
0OKNo issue has been encountered
1UNAUTHORIZEDMissing/wrong credentials or the user does not have enough rights to perform the requested operation
2MISSING_VERSIONThe parameter 'version' is missing
3MISSING_JSONThe parameter 'json_data' is missing
4INVALID_JSONThe input structure is not a valid JSON string
5MISSING_AUTH_USERThe parameter 'auth_user' is missing
6MISSING_AUTH_PWDThe parameter 'auth_pwd' is missing or you are using url login type and it's not allowed on the Configuration file of your iTop
10UNSUPPORTED_VERSIONNo operation is available for the specified version
11UNKNOWN_OPERATIONThe requested operation is not valid for the specified version
12UNSAFEThe requested operation cannot be performed because it can cause data (integrity) loss
100INTERNAL_ERRORThe operation could not be performed, see the message for troubleshooting

Core services

The core service are generic services. They are the equivalent of the iTop Core PHP APIs: DBObject, DBObjectSearch and DBObjectSet.

Using this services, you can manipulate any kind of data, provided you know enough of the classes and their attributes.

How to specify a key

A key is a mean to identify an object. This type of specification can be used to determine the target object for the operation, and it used to determine the value of a external key (or “foreign key”).

Three forms are allowed:

  • Specify the id of the object (as a number):

...
   "key": 123
  • Specify a search query (OQL):

...
   "key": "SELECT UserRequest WHERE caller_name LIKE \"monnet\""
  • Specify search criteria (all criteria are combined with a AND operator):

... "key": { "name": "Monnet", "first_name": "Claude" }

How to specify a value

The value of an attribute is given in a format which depends on the attribute type.

Here is an example that illustrates some cases:

"name": "Monnet", "first_name": "Claude", "age": 80, "picture": { "data": "iVBORw0KGgoAAAAN.......AAAAElFTkSuQmCC", "filename": "smiley.png", "mimetype": "image/png" }

Scalars

For most of the attribute types, the value is simply a scalar.

For the external keys, the value is a key (see definition above).

For text fields formatted as pure text, new lines are specified by the mean of “\”.

Starting with iTop 2.3 the ticket description is formatted in HTML. It is possible to alter the datamodel and turn the description field back into a pure text field, or you will have to transform your data into HTML (carrier returns transformed into <br> tags and escaping HTML entities like '<' or '&'.

Example:

"name": "Monnet", "description": "A famous french artist.\nLaunched the impressionism trend." "presentation": "<p>A famous french artist</p><p>Launched the <em>impressionism</em> trend.</p>" "age": 80, "org_id": "SELECT Organization WHERE name = 'Demo'", "location_id": 3, "supervisor_id": { "name": "Foo", "first_name": "John" }

Blobs

For Blobs (i.e. binary data), the value is given as an array of three items: data, filename and mimetype.

  • 'data' is the binary data that has been base 64 encoded (see PHP/base64_encode)

  • 'filename' is the name of the original file. Its purpose is provide a default file name in case the file gets further downloaded.

  • 'mimetype' must match the format of the file so that iTop can display it correctly.

Example:

"picture": { "data": "iVBORw0KGgoAAAANSUhEUgAAAA8AAAAPCAIAAAC0tAIdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACmSURBVChTfZHRDYMwDESzQ2fqhHx3C3ao+MkW/WlnaFxfzk7sEnE6JHJ+NgaKZN2zLHVN2ssfkae0Da7FQ5PRk/ve4Hcx19Ie6CEGuh/6vMgNhwanHVUNbt73lUDbYJ+6pg8b3+m2RehsVPdMXyvQY+OVkB+Rrv64lUjb3nq+aCA6v4leRqtfaIgimr53atBy9PlfUhoh3fFCNDmErv9FWR6ylBL5AREbmHBnFj5lAAAAAElFTkSuQmCC", "filename": "smiley.png", "mimetype": "image/png" }

Case Log

Starting with iTop 2.3 case logs are formatted in HTML. Therefore, the shorthand syntax expects the comment to be formatted in HTML.

Since iTop 2.0.3, 3 syntaxes are possible for populating “CaseLog” fields: shorthand syntax, single item or whole log.

Shorthand syntax

If a simple text string is supplied, the text will be added as a new entry in the case log with the current date & time and the current user, and the text will be implicitely considered as formatted in HTML.

Example:

"public_log": "blah blah blah",
Rich syntax

If a structure with an entry named add_item is supplied, one can specify additional information:

  • user name (defaults to the credentials used for the REST/JSON API)

  • date/time of the entry (defaults to “now”)

  • format of the comment (defaults to “html”, can be set to “text”)

Example:

"public_log": {
   "add_item":
   {
      "date": "yyyy-mm-dd hh:mm:ss",
      "user_login": "jfoo",
      "message": "The first line\nAnother line",
      "format":"text"
   }
},
Full syntax

If an array named items is suplied, the whole content of the case log will be replaced by the supplied entries.

Example:

"public_log":
{
   "items":
   [
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "<p>The first line</p><p>A second line</p>"
      },
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "<p>The first line</p><p>A second line</p>",
         "format": "html"
      },
      {
         "date": "yyyy-mm-dd hh:mm:ss",
         "user_login": "jfoo",
         "message": "blah blah blah",
         "format": "text"
      }
   ]
},

Link sets

For link sets, the value is an array of object definitions.

Example:

"contacts_list":
[
   {
      "role": "artist",
      "contact_id":
      {
         "finalclass": "Person",
         "name": "monet",
         "first_name": "claude"
      }
   },
   {
      "role": "Basket-ball",
      "contact_id": "SELECT Team WHERE name = 'San Antonio Spurs'"
   },
   {
      "contact_id": 1234
   }
]

Response

The format for the response of core/… operations is the following:

{ "objects": { "objectclass::objectkey": { ... } }, "code": 0, "message": "Found: 1" }

Where each object is the form:

{ "code": 0, "message": "", "class": "Person", "key": 1234, "fields": { "id": 1234, "name": "My last name", "status": "Active", "org_id": 123, ..... ..... ..... } }

The list of attributes given can be controlled by the mean of the parameter output_fields (when available). The parameter output_fields can have the following forms:

  • A list of attribute codes separated by a coma (e.g.: “name, status, org_id”). Only attributes of the queried class can be given here.

  • * means all the attributes of the queried class

  • *+ (since 2.0.3) means all the attributes of each object found (subclasses may have more attributes than the queried class)

Operation: core/get

Searches for a list of objects.

Example:

Passing the following json_data:

{ "operation": "core/get", "class": "Person", "key": "SELECT Person WHERE email LIKE '%.com'", "output_fields": "friendlyname, email" }

or, using another form of “key”:

{ "operation": "core/get", "class": "Person", "key": 1, "output_fields": "*" }

Since 2.6.1 (PR #25, thanks to Dennis Lassiter !), pagination is handled using two new parameters :

  • limit (int): Amount of results to return (default: 0 = no limit)

  • page (int): Page number to return (cannot be < 1)

Records ordering can be controlled using the classes/class/properties/order datamodel XML node.

Example :

{ "operation": "core/get", "class": "Person", "key": "SELECT Person", "output_fields": "friendlyname, email" "limit": "5", "page": "2" }

Operation: core/create

Creates a new object of the given class

Passing the following json_data:

{ "operation": "core/create", "comment": "Synchronization from blah...", "class": "UserRequest", "output_fields": "id, friendlyname", "fields": { "org_id": "SELECT Organization WHERE name = \"Demo\"", "caller_id": { "name": "monet", "first_name": "claude", } "title": "Houston, got a problem!", "description": "The fridge is empty" } }

… will result in a new User Request being created.

Some attributes have a special format:

  • Link sets: only indirect link sets are currently supported, see the example given above

  • Blobs: document contents (e.g. DocumentFile/file) must be in the form {data: base64-encoded-data, mimetype: …, filename: …}

  • Case logs: three forms are allowed.

    •  

    Passing a string is equivalent to adding a new message from within the GUI: the message is recorded on behalf of the current user (credentials used to invoke the web service).

    •  

    Passing a structure in the form {add_item: {message: 'blah', user_id: 123, date:'2012-02-28 10:30'}} adds a single message too. user_id and date are optionals, defaulting respectively to the current user and the current date and time. Specifying user_id requires that the credentials used to invoke the service have Administrator rights, otherwise the operation would fail with UNAUTHORIZED error code.

    •  

    Passing a structure in the form {items: [ {message: 'blah'} ]} sets the entire log.

Example of a response:

{ "code": 0, "message": "", "objects": { "UserRequest::123": { "code": 0, "message": "created", "class": "UserRequest", "key": 29, "fields": { "id": 29, "friendlyname": "R-000029" } } } }

Operation: core/update

Updates one object

Passing the following json_data:

{ "operation": "core/update", "comment": "Synchronization from blah...", "class": "UserRequest", "key": { "description": "The fridge is empty" }, "output_fields": "friendlyname, title, contact_list", "fields": { "contacts_list": [ { "role": "pizza delivery", "contact_id": { "finalclass": "Person", "name": "monet", "first_name": "claude" } } ] } }

… will update the User Request (identified by its description “The fridge is empty”) by setting the contact list to one contact (Claude Monet) and the role 'pizza delivery'.

Multiple (bulk) updates are not supported If the key specification matches more than one object the update will fail with the error: Several items found (xx) for query….

Operation: core/apply_stimulus

Updates one object and applies a stimulus to change the state of the object

Passing the following json_data:

{ "operation": "core/apply_stimulus", "comment": "Synchronization from blah...", "class": "UserRequest", "key": 15, "stimulus": "ev_assign", "output_fields": "friendlyname, title, status, contact_list", "fields": { "team_id": 18, "agent_id": 57 } }

… will update the User Request (identified by its key “15”) by setting the agent_id and team_id fields (which are mandatory for the state assigned) and then will apply the stimulus ev_assign that causes the ticket to transition from the state new to the state assigned.

Multiple (bulk) apply_stimulus are not supported in this first version. If the key specification matches more than one object the update will fail with the error: Several items found (xx) for query….

Operation: core/delete

Delete a set of objects

Passing the following json_data:

{ "operation": "core/delete", "comment": "Cleanup for customer Demo", "class": "UserRequest", "key": { "org_id": 2 }, "simulate": false }

… will delete User Request of the customer #2.

A deletion may imply the deletion and/or update of other objects which are linked to the deleted objects. All the objects are listed in the report.

Use simulate: true to finetune your script

Each object reported has a deletion status code and a message giving additional information. The status codes are defined in core/restservices.class.inc.php, as constants of the class RestDelete:

ValueConstantMeaning
0OKObject deleted as per the initial request
1ISSUEGeneral issue (user rights or … ?)
2AUTO_DELETEMust be deleted to preserve database integrity
3AUTO_DELETE_ISSUEMust be deleted to preserve database integrity, but that is NOT possible
4REQUEST_EXPLICITELYMust be deleted to preserve database integrity, but this must be requested explicitely
5AUTO_UPDATEMust be updated to preserve database integrity
6AUTO_UPDATE_ISSUEMust be updated to preserve database integrity, but that is NOT possible

Searches for related objects.

Given an object or a list of objects, searches for other objects that are impacting or impacted by those objects.

Passing the following json_data:

{ "operation": "core/get_related", "class": "Server", "key": 1, "relation": "impacts", "depth": 4, "redundancy": true, "direction": "down" }

… will search for all of the CIs that Server::1 does impact. The search depth is limited to 4 iterations (defaults to 20).

The results will be in the form:

{ "objects": { "objectclass::objectkey": { ... } }, "relations": { "origin-class::origin-key": [ { "key": "destination-class::destination-key" } ] }, "code": 0, "message": "Scope: 1; Found: Server=4, VirtualMachine=3, Farm=1" }

The search can be performed on a list of objects. Simply specify the input parameter 'key' as an OQL like “SELECT Server” and all CIs related to any server will be considered. In the results sumary, this is what is referred to as “scope”.

Operation: core/check_credentials

Checks a user login + password.

Passing the following json_data:

{ "operation": "core/check_credentials", "user": "john", "password": "abc123", }

… will reply (if everything went well)…

{ "code": 0, "message": "", "authorized": true, }

Starting with iTop 2.3.0 it is possible to deactivate an account (by setting its status to “Disabled”). When an account is disabled, check_credentials returns authorized: false.

Example and playground

If you have an iTop already installed (version 2.0.1+), then click here to test the REST API.

Here is the corresponding code: jsfiddle playground

Example of how you can integrate REST/JSON calls: using bash and wget

How to add services

It is possible to extend the services by developping a module (or extension) that declares a class (included in your custom module) implementing the interfaceiRestServiceProvider.

As soon as your module is installed, your custom services will be available and listed with operation=list_operations.

Changes history

iTop versionJSON REST versionChanges
2.0.11.0Created
2.0.21.1Added 'key' to the returned object information (required some parsing in 1.0), Turned the object search criteria into a strict search (as opposed to a loose search: contains …), Allow to reset an external key (set to 0, meaning “undefined”)
2.0.31.2Fully handle the case logs (could be entirely read or written), Enums/GET giving the raw value not the localized label, Allow the HTTP basic authentication method, Added the verb core/check_credentials, Improved the error reporting (missing authentication arguments, wrong class for writing a link set), Added the option *+ to output all the fields of the object (not only the fields of the queried class), Fixed the report on object deletion
2.2.01.3Verb get_related: added the options redundancy and direction to take into account the redundancy in the impact analysis. For security reasons, the use of REST/JSON webservices by user accounts with the profile Portal User is now disabled. If you use one of the webservices only to check the credentials of a user, adjust your code to use the core/check_credentials operation. For security reasons, the operations core/get andcore/get_related are now only allowed to users having the bulk read privilege on the specified class of objects.
2.5.2, 2.6.1, 2.7.01.4Verb core/get : added pagination parameters limit and page
标签:
由 superadmin 在 2020/08/27, 16:22 创建
    

需要帮助?

如果您需要有关XWiki的帮助,可以联系:

深圳市艾拓先锋企业管理咨询有限公司