JSON-RPC

Материал из support.qbpro.ru

JSON-RPC 2.0 Specification

оригинал:http://www.jsonrpc.org/specification

для справки: Введение в JSON

(выборочный перевод)


Overview

JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol. Primarily this specification defines several data structures and the rules around their processing. It is transport agnostic in that the concepts can be used within the same process, over sockets, over http, or in many various message passing environments. It uses JSON (RFC 4627) as data format.

It is designed to be simple! Он разработан, что бы быть простым


Conventions

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

Since JSON-RPC utilizes JSON, it has the same type system (see http://www.json.org or RFC 4627). JSON can represent four primitive types (Strings, Numbers, Booleans, and Null) and two structured types (Objects and Arrays). The term "Primitive" in this specification references any of those four primitive JSON types. The term "Structured" references either of the structured JSON types. Whenever this document refers to any JSON type, the first letter is always capitalized: Object, Array, String, Number, Boolean, Null. True and False are also capitalized.

All member names exchanged between the Client and the Server that are considered for matching of any kind should be considered to be case-sensitive. The terms function, method, and procedure can be assumed to be interchangeable.

The Client is defined as the origin of Request objects and the handler of Response objects. The Server is defined as the origin of Response objects and the handler of Request objects.

One implementation of this specification could easily fill both of those roles, even at the same time, to other different clients or the same client. This specification does not address that layer of complexity.

Compatibility

JSON-RPC 2.0 Request objects and Response objects may not work with existing JSON-RPC 1.0 clients or servers. However, it is easy to distinguish between the two versions as 2.0 always has a member named "jsonrpc" with a String value of "2.0" whereas 1.0 does not. Most 2.0 implementations should consider trying to handle 1.0 objects, even if not the peer-to-peer and class hinting aspects of 1.0.

Объект Запрос (Request object)

A rpc call is represented by sending a Request object to a Server. The Request object has the following members: Rpc-вызов представляет собой посланный серверу объект запроса (одиночный JSON элемент или массив JSON элементов(пакет)). Каждый объект запроса состоит из следующих частей:

jsonrpc

Строка (тип String) указывающая версию JSON-RPC протокола. ДОЛЖНО быть указано "2.0".

method

Строка (тип String) содержащая имя вызываемого метода (функции). Имя метода должно начинаться с буквы начиная с кода (U+002E или ASCII 46) и передаваться только внутренним методам и расширениям RPC и больше НИ ГДЕ не использоваться.

params

Необязательный параметр, содержащий структуру данных, содержащую исходные данные, которые будут использоваться при вызове метода. Этот параметр МОЖЕТ быть пропущен (необязательный).

id

Необязательный параметр (тип String, Number или NULL), содержащий идентификатор устанавливаемый клиентом. Если не указан, то предполагается, что данный запрос - уведомление (не полежит ответу). Значением может быть Null или число, не имеющее дробной десятичной части.

Сервер ОБЯЗАН включить это же значение id в объект ответа. id используется клиентом для установления связи между отправленным запросом и полученным ответом.


Уведомление (Notification)

Уведомление - это запрос без параметра "id". Объект запроса, сформированный как уведомление означает, что клиент не ждет на него ответа, соответственно не надо возвращать объект ответа клиенту. Сервер НЕ ДОЛЖЕН отвечать на уведомления, в том числе полученные в составе пакетного запроса. Уведомления не подтверждаемы по определению, так как они не имеют ответа объекта, который необходимо вернуть.Таким образом, клиент не будет знать о каких-либо ошибках (таких как "Invalid params.","Internal error.").

Структура параметров

Если параметры присутствуют в rpc-запросе, они ДОЛЖНЫ быть представлены структурой. Или позиционным массивом или именованными параметрами в виде объекта JSON.

  • Позиционный массив: ОБЯЗАТЕЛЬНО массив, содержащий значения обрабатываемые сервером в указанном порядке.
  • Именованные параметры: ОБЯЗАТЕЛЬНО объект (пары ключ:значение в формате JSON), с именами ключей, совпадающих с именами параметров, обрабатываемых сервером.

Отсутствие правильных имен ключей ДОЛЖНО (И ОБЯЗАТЕЛЬНО ЭТО ПРОИЗОЙДЕТ) вызывать ошибку. Имена ключей должны совпадать с именами параметров в вызываемом методе.

Response object

When a rpc call is made, the Server MUST reply with a Response, except for in the case of Notifications. The Response is expressed as a single JSON Object, with the following members:

jsonrpc

A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".

result

This member is REQUIRED on success. This member MUST NOT exist if there was an error invoking the method. The value of this member is determined by the method invoked on the Server.

error

This member is REQUIRED on error. This member MUST NOT exist if there was no error triggered during invocation. The value for this member MUST be an Object as defined in section 5.1.

id

This member is REQUIRED.

It MUST be the same as the value of the id member in the Request Object.

If there was an error in detecting the id in the Request object (e.g. Parse error/Invalid Request), it MUST be Null.

Either the result member or error member MUST be included, but both members MUST NOT be included.

Error object

When a rpc call encounters an error, the Response Object MUST contain the error member with a value that is a Object with the following members:

code

A Number that indicates the error type that occurred. This MUST be an integer.

message

A String providing a short description of the error. The message SHOULD be limited to a concise single sentence.

data

A Primitive or Structured value that contains additional information about the error.

This may be omitted.

The value of this member is defined by the Server (e.g. detailed error information, nested errors etc.).

The error codes from and including -32768 to -32000 are reserved for pre-defined errors. Any code within this range, but not defined explicitly below is reserved for future use. The error codes are nearly the same as those suggested for XML-RPC at the following url: http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php


code
message
meaning
-32700 Parse error Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
-32600 Invalid Request The JSON sent is not a valid Request object.
-32601 Method not found The method does not exist / is not available.
-32602 Invalid params Invalid method parameter(s).
-32603 Internal error Internal JSON-RPC error.
-32000 to -32099 Server error Reserved for implementation-defined server-errors. The remainder of the space is available for application defined errors.


Код
Сообщение
Значение сообщения
-32700 Ошибка разбора Невалидный (неправильно отформатированный JSON) был передан серверу. Ошибка генерируется во время разбора JSON текста.
-32600 Неверный запрос Послан неверный JSON объект запроса.
-32601 Метод не найден Метод отсутствует или недоступен.
-32602 Неверные параметры Неправильный параметр(ы) вызываемого метода.
-32603 Внутренняя ошибка Внутренняя JSON-RPC ошибка.
с -32000 по -32099 Ошибки сервера Ошибки сервера вызванные и описанные в приложениях.

Пакетный запрос (Batch)

Чтобы отправить составной запрос (пакет) с несколькими объектами-запросами, клиент должен отправить массив заполненный объектами запросов.

Сервер должен среагировать на переданные массив объектов запросов только после предварительной обработки всего пакета. Объект ответа должен быть создан для КАЖДОГО объекта запроса, исключая уведомления, на которые не могут быть созданы какие-либо объекты ответы. The Server MAY process a batch rpc call as a set of concurrent tasks, processing them in any order and with any width of parallelism.

The Response objects being returned from a batch call MAY be returned in any order within the Array. The Client SHOULD match contexts between the set of Request objects and the resulting set of Response objects based on the id member within each Object.

If the batch rpc call itself fails to be recognized as an valid JSON or as an Array with at least one value, the response from the Server MUST be a single Response object. If there are no Response objects contained within the Response array as it is to be sent to the client, the server MUST NOT return an empty Array and should return nothing at all.

Examples

Синтаксис

--> данные отправляемые серверу
<-- данные возвращаемые клиенту

rpc-вызов с позиционными параметрами (в виде массива):

--> {"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
<-- {"jsonrpc": "2.0", "result": 19, "id": 1}

--> {"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}
<-- {"jsonrpc": "2.0", "result": -19, "id": 2}

rpc-вызов с именованными параметрами (в виде объекта):

--> {"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}
<-- {"jsonrpc": "2.0", "result": 19, "id": 3}

--> {"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}
<-- {"jsonrpc": "2.0", "result": 19, "id": 4}

rpc-вызов - уведомление (примечание: отсутствует параметр id/(id и params), обратного ответа не одидают):

--> {"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}
--> {"jsonrpc": "2.0", "method": "foobar"}

rpc-вызов не являющегося исполняемым/отсутствующего метода:

--> {"jsonrpc": "2.0", "method": "foobar", "id": "1"}
<-- {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "1"} 

rpc-вызов с невалидным JSON (в параметрах неправильно перечислены 2 параметра (не массив и не объект)):

--> {"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]
<-- {"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error."}, "id": null}

rpc-вызов с невалидным JSON в объекте запроса (имя метода задано числом):

--> {"jsonrpc": "2.0", "method": 1, "params": "bar"}
<-- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null}

пакетный rpc-вызов, невалидный JSON в одном из запросов:

--> [
  {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
  {"jsonrpc": "2.0", "method"
]
<-- {"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error."}, "id": null}

rpc-вызов, пустой массив:

--> []
<-- {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null}

пакетный rpc-вызов, неправильный, но не пустой пакет:

--> [1]
<-- [
  {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null}
]

пакетный rpc-вызов, неправильный пакет:

--> [1,2,3]
<-- [
  {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
  {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
  {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null}
]

пакетный rpc-вызов:

--> [
        {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
        {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
        {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
        {"foo": "boo"},
        {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
        {"jsonrpc": "2.0", "method": "get_data", "id": "9"} 
    ]
<-- [
        {"jsonrpc": "2.0", "result": 7, "id": "1"},
        {"jsonrpc": "2.0", "result": 19, "id": "2"},
        {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
        {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"},
        {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
    ]

пакетный rpc-вызов (все уведомления):

--> [
        {"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]},
        {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}
    ]
<-- //Возвращать нечего (нет ответов не на один запрос, поскольку не укан ни один параметр id в запросах)

Extensions

Method names that begin with rpc. are reserved for system extensions, and MUST NOT be used for anything else. Each system extension is defined in a related specification. All system extensions are OPTIONAL.

Copyright (C) 2007-2010 by the JSON-RPC Working Group

This document and translations of it may be used to implement JSON-RPC, it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not bemodified in any way.

The limited permissions granted above are perpetual and will not be revoked.

This document and the information contained herein is provided "AS IS" and ALL WARRANTIES, EXPRESS OR IMPLIED are DISCLAIMED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.