REST API

From OpenCog

(Redirected from Web Interface)
Jump to: navigation, search

Contents

Interactive Documentation

As described in more detail below, the REST API has interactive documentation that can be browsed at the following URL:

http://opencog.github.io/rest-api-documentation/

Overview

Exposes a REST API for the AtomSpace, the CogServer Scheme shell, and the CogServer control commands.

Implemented in Python using the Flask micro-framework and Flask-RESTful extension.

See also: API

Configuration

Prerequisites

Requires OpenCog Python to be set-up properly

To do so, follow these instructions: https://github.com/opencog/opencog/blob/master/opencog/python/README.md

After that, everything should work properly. The following instructions are not necessary, unless you are using a config file other than the default.

Instructions for non-default config files:

PYTHON_EXTENSION_DIRS must specify the relative location of the API scripts

Example:

PYTHON_EXTENSION_DIRS = ../opencog/python/web/api

Example if your OpenCog source directory is in ~/git/opencog and your build directory is in ~/git/opencog_build:

PYTHON_EXTENSION_DIRS  = ../opencog/opencog/python/web/api,
                         ../opencog/opencog/python/pln,
                         ../opencog/tests/python/test_pln

PYTHON_PRELOAD must specify the restapi module

Example:

PYTHON_PRELOAD = restapi

Starting the REST API

To start the REST API, type restapi.Start at the CogServer shell.

If you get: command "restapi.Start" not found, first check:

loadpy restapi

If you get: command "loadpy" not found then you haven't properly configured Python bindings.

After you can get loadpy command to work, you should be able to call restapi.Start. If so then check lib/opencog.conf to make restapi automatically preloaded without needing loadpy.

Endpoint

Default Endpoint

The default endpoint is: http://127.0.0.1:5000/api/v1.1/

Accessing this URL directly will give 404 File Not Found error, you need to access specific subresources as described below.

The IP address and port number are passed as an argument when instantiating the RESTAPI class. By default, it is setup for local access only, by assigning 127.0.0.1 as the IP address.

Optional settings

The following changes should be made in opencog/python/web/api/restapi.py#L9:

Allowing external access

To allow external access, change 127.0.0.1 to 0.0.0.0. Then, you will be able to use the external IP address of your server in the endpoint URL.

Choosing a different port

To modify the port used, edit the value of the PORT parameter

Example request

Return all Atoms of type ConceptNode

curl 'http://localhost:5000/api/v1.1/atoms?type=ConceptNode'

Error handling

The REST API returns HTTP response codes. A successful request returns code 200, while error conditions return 400, 404, or 500, indicating the type of the error. When an error occurs, a detailed message is also returned describing the cause of the error.

Example: 400 Bad Request

Invalid request: truthvalue details object requires both a strength and count parameter

Interactive API Documentation

OpenCog REST API comes with built-in user-friendly interactive API documentation powered by Swagger. In addition to browsing documentation for each endpoint easily, you can also play with the API directly without any coding by filling parameters using the dynamic AJAX UI.

Can be accessed at:

Restswagger.png

Original pull request at [1] --Hendy (talk) 23:13, 13 July 2014 (CDT)

Notes & Known Issues:

  • For POST/PUT endpoints, to make documentation easier to read each parameter is listed as form, however in reality they're part of the JSON body's schema. So currently the "Test It Now" functionality of those endpoints don't work as intended. To fix it then either we should make the endpoints understand form parameters as well as JSON, or fix the Swagger annotations to include proper Model schema. Additionally we can suggest or contribute to Swagger (2.0?) project so that Swagger UI can compose simple JSON documents on the fly, but that's probably out of scope. --Hendy (talk) 23:13, 13 July 2014 (CDT)

Public OpenCog REST API Documentation (without live OpenCog server) is available at OpenCog REST API Documentation.


API Schemas

Response Format

The REST API returns one of the following response types:

  • atom collection
  • types
  • shell
  • scheme

Atom Collection

An atom collection is a list of atoms with the following format:

{
  'atoms':
  [
  {
    'handle': UUID,
    'name': NAME,
    'type': TYPENAME,
    'outgoing': [ UUID1, UUID2 ... ],
    'incoming': [ UUID1, UUID2 ... ],
    'truthvalue':
      {
        'type': TRUTHVALUETYPE,
        'details':          
		TRUTHVALUEDETAILS
      },
  'attentionvalue':
    {
      'lti': LTI,
      'sti': STI,
      'vlti': VLTI
    }
  }
        ...
  ]
}

Atom

An atom is returned in the following format:

{
  'atoms':
  {
    'handle': UUID,
    'name': NAME,
    'type': TYPENAME,
    'outgoing': [ UUID1, UUID2 ... ],
    'incoming': [ UUID1, UUID2 ... ],
    'truthvalue':
      {
        'type': TRUTHVALUETYPE,
        'details':          
		TRUTHVALUEDETAILS
      },
  'attentionvalue':
    {
      'lti': LTI,
      'sti': STI,
      'vlti': VLTI
    }
  }
}

Detailed description

Atom

handle Atom handle
UUID integer
outgoing (optional) The set of arguments of the relation, formatted as a list of Atom handles
(only valid for Links, not nodes), see Incoming and Outgoing Sets
OUTGOING list of integers
incoming (optional) The set of relationships that take this atom as an argument, formatted as a list of Atom handles
see Incoming and Outgoing Sets
INCOMING list of integers
type (optional)
Atom type, see OpenCog Atom types
TYPENAME string (choose from the list of available atom types)
name (optional, not allowed for Link types) Atom name
NAME string
truthvalue (optional) TruthValue
type (required) TruthValue type
TRUTHVALUETYPE string (choose from the list of available TruthValue types. Currently available types are: simple)
see TruthValue
details (required)
TRUTHVALUEDETAILS see below
attentionvalue (optional) AttentionValue, formatted as follows:
sti (optional) Short-Term Importance
STI int
lti (optional) Long-Term Importance
LTI int
vlti (optional) Very-Long Term Importance
VLTI boolean

TruthValue details

TruthValue parameter, formatted as follows:

TRUTHVALUEDETAILS
strength (required)
count (required)
Note: Other TruthValue types have not been implemented yet in the Cython bindings, which are what the REST API uses to interface with the AtomSpace. To support additional TruthValue types in the REST API, the Cython bindings need to be enhanced.

JSON representation:

{
    'count': TRUTHVALUECOUNT,
    'confidence': TRUTHVALUECONFIDENCE,
    'strength': TRUTHVALUESTRENGTH
}
TRUTHVALUECOUNT float
TRUTHVALUECONFIDENCE float
TRUTHVALUESTRENGTH float

Documentation

Please refer to OpenCog REST API Documentation.

Example usage in Python

Examples are provided to demonstrate how to consume the REST API using Python and the Python Requests library.

The examples are available in opencog/python/web/api/exampleclient.py.

Development

The opencog/python/web/api/restapi.py file implements a CogServer Module to load upon startup that will load the REST API defined in opencog/python/web/api/apimain.py.

Source

The source is located in the opencog/python/web/api directory.

JSONP & CORS Support

The Flask server sets the CORS headers in the response to allow for cross-origin access from web browser applications. For browsers that do not recognize CORS headers, there is a JSONP option. To use JSONP, pass the name of your JavaScript callback function as a parameter in the request. The parameter name must be callback and the value is any valid JavaScript function name. Example: http://127.0.0.1:5000/api/v1.1/atoms?callback=foo. Note that at present, only GET request types are supported.

Unit Tests

Unit tests are located in tests/python/test_restapi.py

Potential Additions

Potential additions to the REST API include:

  • Change implementation so that it runs as an ordinary opencog Agent; that way, the agent infrastructure can be used to stop & start the thing.
  • Change STI & LTI to update with deltas, instead of absolute values. Thus, if some other agent updates an STI or LTI at the same time that some REST user does, the REST user will not clobber the update. At most, it can add or subtract to the current STI/LTI. (Requires modifying the underlying code)
  • Add a CogServer resource to enable control of CogServer requests (Requires modifying the underlying code)
  • Support pagination
  • Support sort parameters such as STI
  • Support advanced filter parameters, such as combining a type filter parameter with an AttentionalFocus filter parameter (Requires modifying the underlying code)
  • Support atom search by incoming or outgoing set (Requires modifying the underlying code)
  • Add authentication