github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-core-master/docs/source/architecture/rest_api.rst (about)

     1  ********
     2  REST API
     3  ********
     4  
     5  *Hyperledger Sawtooth* provides a pragmatic RESTish API for clients to interact
     6  with a validator using common HTTP/JSON standards. It is an entirely separate
     7  process, which once running, allows transactions to be submitted and blocks to
     8  be read with a common language-neutral interface. As the validator is redesigned
     9  and improved the REST API will grow with it, providing a consistent interface
    10  that meets the needs of application developers into the future.
    11  
    12  With that focus on application developers, the REST API treats the validator
    13  mostly as a
    14  black box, submitting transactions and fetching the results. It is not the tool
    15  for all validator communication. For example, it is not used by Transaction
    16  Processors to communicate with a validator, or by one validator to talk to other
    17  validators. For these and similar use cases, there is a more efficient and
    18  robust, if somewhat more complicated, ZMQ/Protobuf interface.
    19  
    20  
    21  Open API Specification
    22  ======================
    23  
    24  The REST API is comprehensively documented using the
    25  `OpenAPI specification <http://swagger.io/specification/>`_ (fka Swagger),
    26  formatted as a YAML file. This documentation provides a single source of truth
    27  that completely documents every implemented aspect of the API, is both human and
    28  machine readable, and can be compiled by a variety of toolsets (including for
    29  this Sphinx-based document). The spec file itself can be found
    30  `here <https://github.com/hyperledger/sawtooth-core/blob/master/rest_api/openapi.yaml>`_.
    31  
    32  
    33  HTTP Status Codes
    34  =================
    35  
    36  In order to improve clarity and ease parsing, the REST API supports a limited
    37  number of common HTTP status codes. Further granularity for parsing errors is
    38  provided by specific :doc:`../rest_api/error_codes` in the JSON response
    39  envelope itself (see below).
    40  
    41  .. list-table::
    42     :widths: 4, 16, 60
    43     :header-rows: 1
    44  
    45     * - Code
    46       - Title
    47       - Description
    48     * - 200
    49       - OK
    50       - The requested resources were successfully fetched. They are included in
    51         the ``"data"`` property of the response envelope.
    52     * - 201
    53       - Created
    54       - The POSTed resources were submitted and created/committed successfully. A
    55         ``"link"`` is included to the resources.
    56     * - 202
    57       - Accepted
    58       - The POSTed resources were submitted to the validator, but are not yet
    59         committed. A ``"link"`` to check the *status* of the submitted resources
    60         is included. If told to wait for commit, but timed out, the status at the
    61         moment of timing out is also included in the ``"data"`` property.
    62     * - 400
    63       - Bad Request
    64       - Something in the client's request was malformed, and the request could
    65         not be completed.
    66     * - 404
    67       - Not Found
    68       - The request was well-formed, but there is no resource with the identifier
    69         specified.
    70     * - 500
    71       - Internal Server Error
    72       - Something is broken in the REST API or the validator. If consistently
    73         reproducible, a bug report should be submitted.
    74     * - 503
    75       - Service Unavailable
    76       - Indicates the REST API is unable to contact the validator.
    77  
    78  
    79  Data Envelope
    80  =============
    81  
    82  The REST API uses a JSON envelope to send metadata back to clients in a way that
    83  is simple to parse and easily customized. All successful requests will return
    84  data in an envelope with at least one of four possible properties:
    85  
    86     * **data** - contains the actual resource or resources being fetched
    87     * **head** - id of the head block of the chain the resource was fetched
    88       from, this is particularly useful to know if an explicit *head* was not set
    89       in the original request
    90     * **link** - a link to the resources fetched with both *head* and
    91       paging parameters explicitly set, will always return the same resources
    92     * **paging** - information about how the resources were paginated, and how
    93       further pages can be fetched (see below)
    94  
    95  *Example response envelope:*
    96  
    97  .. code-block:: json
    98  
    99     {
   100       "data": [{"fetched": "resources"}],
   101       "head": "65cd...47dd",
   102       "link": "http://rest.api.domain/state?head=65cd...47dd"
   103     }
   104  
   105  
   106  Pagination
   107  ----------
   108  All endpoints that return lists of resources will automatically paginate
   109  results, limited by default to 1000 resources. In order to specify what range of
   110  resources to return, these endpoints take ``count`` and either ``min`` or
   111  ``max`` query parameters. They specify the total number of items to include, as
   112  well as what the first or last item in the list should be. For convenience,
   113  both *min* and *max* may refer to either an index or a resource id.
   114  
   115  *Example paged request URL:*
   116  
   117  .. code-block:: text
   118  
   119     http://rest.api.domain/blocks?count=100&min=200
   120  
   121  Within the ``"paging"`` property of the response body there will be one or more
   122  of these four values:
   123  
   124     * **start_index** - index of the first item in the fetched list
   125     * **total_count** - total number of resources available
   126     * **previous** - URL for the previous page, if any
   127     * **next** - URL for the next page, if any
   128  
   129  *Example paging response:*
   130  
   131  .. code-block:: json
   132  
   133     {
   134       "data": [{"fetched": "resources"}],
   135       "paging": {
   136         "start_index": 200,
   137         "total_count": 54321,
   138         "previous": "http://rest.api.domain/state?head=65cd...47dd&count=100&min=100",
   139         "next": "http://rest.api.domain/state?head=65cd...47dd&count=100&min=300"
   140       }
   141     }
   142  
   143  
   144  Errors
   145  ------
   146  
   147  If something goes wrong while processing a request, the REST API will send back
   148  a response envelope with only one property: ``"error"``. That error will contain
   149  three values which explain the problem that occurred:
   150  
   151     * **code** - machine-parsable code specific to this particular error
   152     * **title** - short human-readable headline for the error
   153     * **message** - longer more detailed explanation of what went wrong
   154  
   155  *Example error response:*
   156  
   157  .. code-block:: json
   158  
   159     {
   160       "error": {
   161         "code": 30,
   162         "title": "Submitted Batches Invalid",
   163         "message": "The submitted BatchList is invalid. It was poorly formed, or has an invalid signature."
   164       }
   165     }
   166  
   167  .. note::
   168  
   169     While the title or message of an error may change or be reworded over time,
   170     **the code is fixed**, and will always refer to the same error.
   171  
   172  
   173  Query Parameters
   174  ================
   175  
   176  Many routes support query parameters to help specify how a request to the
   177  validator should be formed. Not every endpoint supports every query, and some
   178  endpoints have their own parameters specific to just to them. Any queries
   179  specific to a single endpoint are not listed here.
   180  
   181  .. list-table::
   182     :widths: 8, 72
   183  
   184     * - **head**
   185       - The id of the block to use as the chain head. This is particularly
   186         useful to request older versions of state *(defaults to the latest chain
   187         head)*.
   188     * - **count**
   189       - For paging, this item specifies the number of resources to fetch
   190         *(defaults to 1000)*.
   191     * - **min**
   192       - For paging, specifies the id or index of the first resource to fetch
   193         *(defaults to 0)*.
   194     * - **max**
   195       - For paging, specifies the id or index of the last resource to fetch. It
   196         would be used instead of *min*, not in the same query.
   197     * - **sort**
   198       - For endpoints that fetch lists of resources, specifies a key or keys to
   199         sort the list by. These key sorts can be modified with a few simple
   200         rules: nested keys can be dot-notated; `header.` may be omitted in the
   201         case of nested header keys; appending `.length` sorts by the length of
   202         the property; a minus-sign specifies descending order; multiple keys can
   203         be used if comma-separated. For example:
   204         `?sort=header.signer_public_key,-transaction_ids.length`
   205     * - **wait**
   206       - For submission endpoints, instructs the REST API to wait until batches
   207         have been committed to the blockchain before responding to the client.
   208         Can be set to a positive integer to specify a timeout in seconds, or
   209         without any value to use the REST API's internal timeout.
   210  
   211  
   212  Endpoints
   213  =========
   214  
   215  The endpoints include RESTful references to resources stored in the Sawtooth
   216  ledger that clients might be interested in, like blocks and transactions, as
   217  well as RESTish metadata, like batch status.
   218  
   219  
   220  Resource Endpoints
   221  ------------------
   222  In order to fetch resources stored on chain or in the validator's state,
   223  various resource routes are provided. As is typical with RESTful APIs, a ``GET``
   224  request fetches one or many resources, depending on whether or not a particular
   225  resource identifier was specified (i.e., ``/resources`` vs
   226  ``/resources/{resource-identifier}``).
   227  
   228     * **/blocks** - the actual blocks currently in the blockchain, referenced by
   229       id (aka ``header_signature``)
   230     * **/batches** - the batches stored on the blockchain, referenced by id
   231     * **/transactions** - the transactions stored on the blockchain, referenced
   232       by id
   233     * **/state** - the ledger state, stored on the Merkle-Radix tree, referenced by
   234       leaf addresses
   235  
   236  
   237  Submission Endpoints
   238  --------------------
   239  In order to submit transactions to a Sawtooth validator, they *must* be wrapped
   240  in a batch. For that reason, submissions are sent to the ``/batches`` endpoint
   241  and only that endpoint. Due to the asynchronous nature of blockchains, there is
   242  a corresponding endpoint to check the status of submitted batches. Both requests
   243  will accept the ``wait`` query parameter, allowing clients to receive a response
   244  only once the batches are committed.
   245  
   246     * **/batches** - accepts a ``POST`` request with a body of a binary
   247       BatchList of batches to be submitted
   248     * **/batch_statuses** - fetches the committed status of one or more batches
   249  
   250       *Example batch status response:*
   251  
   252       .. code-block:: json
   253  
   254          [
   255            {
   256              "id": "89807bfc9089e37e00d87d97357de14cfbc455cd608438d426a625a30a0da9a31c406983803c4aa27e1f32a3ff61709e8ec4b56abbc553d7d330635b5d27029c",
   257              "status": "COMMITTED"
   258            },
   259            {
   260              "id": "c0c2075e708c04b34903c5374f65c9352f9dc9662f187e4bab0605aba3eb697e459bfa3a61a8050c428d1347d47a11b0cf81d481467a18cd48ab137001a5fa29",
   261              "status": "PENDING"
   262            }
   263          ]
   264  
   265  
   266  Future Development
   267  ==================
   268  
   269  Stats and Status Endpoints
   270  --------------------------
   271  
   272  In order to track the performance of the validator and the blockchain generally,
   273  additional endpoints could be implemented to fetch metrics related to block
   274  processing, peer to peer communication, system status, and more. These will
   275  require significant design and development, both within the REST API, and within
   276  the core validator code itself.
   277  
   278  
   279  Configuration
   280  -------------
   281  
   282  At some point it may be useful to add some configuration options to the REST
   283  API, such as:
   284  
   285     * Modify error verbosity to change detail and security sensitivity of error
   286       messages provided (i.e. whether or not to include the stack trace)
   287     * Enable or disable the stats and status endpoints
   288  
   289  
   290  Authorization
   291  -------------
   292  
   293  The current intention is for the REST API to be a lightweight shim on top of the
   294  internal ZMQ communications. From this perspective, the API offers no
   295  authorization, simply passing through every request to the validator to be
   296  authorized with signature verification or some other strategy defined by an
   297  individual Transaction Processor.
   298  
   299  However, that may be insufficient if the API needed to be deployed just for
   300  certain authorized clients. In that use case, the best solution would be to
   301  expand the REST API to handle the validation of *API keys*. In their most basic
   302  form, these can be validated programmatically without any need for persistent
   303  state stored on a database or elsewhere. However, more sophisticated
   304  functionality, like blacklisting particular keys that are compromised, would
   305  require some strategy for persistent storage.
   306  
   307  .. note::
   308  
   309     While the REST API does not support any sort of authorization internally, it
   310     is entirely possible to put it behind a proxy that does. See:
   311     :doc:`/sysadmin_guide/rest_auth_proxy`
   312  
   313  .. Licensed under Creative Commons Attribution 4.0 International License
   314  .. https://creativecommons.org/licenses/by/4.0/