REST API

From OpenCog

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

Contents

Overview

Exposes a REST API for the AtomSpace.

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

Configuration

Prerequisites

Requires installation of the Python dependencies by running this script from your OpenCog source directory:

cd opencog/python/web/api/
sudo ./install_dependencies.sh
Note: After GitHub issue [#337] is addressed, these dependencies will be moved into dependencies.txt or the appropriate location for automatic configuration

Requires the configuration file (opencog.conf) to contain the following parameters:

PYTHON_EXTENSION_DIRS must specify the relative location of the API scripts

Example:

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

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.

Endpoint

Default Endpoint

The default endpoint is:

http://127.0.0.1:5000/api/v1.0/

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 restapi.py:

https://github.com/opencog/opencog/blob/master/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

http://127.0.0.1:5000/api/v1.0/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

AtomSpace Resources

In the following sections, combine the Endpoint with the URI for the resource to generate the full request URL.

Format of Atom and Atom Collection objects

The REST API returns one of the following response types:

  • atom collection
  • types

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

Atom Collection

GET

Returns a list of atoms matching the specified criteria

Uri: ```atoms/[id]```

 (or)

```atoms?type=[type]&name=[name]&filterby=[filterby]&tvStrengthMin=[tvStrengthMin]

           &tvConfidenceMin=[tvConfidenceMin]&tvCountMin=[tvCountMin]&includeIncoming=[includeIncoming]
           &includeOutgoing=[includeOutgoing]&callback=[callback]```

Parameters:

type (optional)
Atom type, see OpenCog_Atom_types
name (optional, not allowed for Link types) Atom name
filterby (optional, can't be combined with type or name)
Allows certain predefined filters:
stirange allows the additional parameters stimin (required) and stimax (optional) and returns the atoms in a given STI range
attentionalfocus returns the atoms in the AttentionalFocus
tvStrengthMin (optional, float) Only return atoms with TruthValue strength greater than this amount
tvConfidenceMin (optional, float) Only return atoms with TruthValue confidence greater than this amount
tvCountMin (optional, float) Only return atoms with TruthValue count greater than this amount
includeIncoming (optional, boolean) Returns the conjunction of the set of atoms and their incoming sets
includeOutgoing (optional, boolean) Returns the conjunction of the set of atoms and their outgoing sets. Useful in combination with includeIncoming.
callback (optional) JavaScript callback function for JSONP support
If neither type or name or filterby are provided, all atoms will be retrieved

Returns:

result JSON representation of an atom list

Example response:

{
  'result':
  {
    'complete': 'true',
    'skipped': 'false',
    'total': 10,
    'atoms':
      [
        { 'handle': 6,
          'name': '',
          'type': 'InheritanceLink',
          'outgoing': [2, 1],
          'incoming': [],
          'truthvalue':
            {
              'type': 'simple',
              'details':
                {
                  'count': '0.4000000059604645',
                  'confidence': '0.0004997501382604241',
                  'strength': '0.5'
                }
            }
          'attentionvalue':
            {
              'lti': 0,
              'sti': 0,
              'vlti': false
            }
        },
             ...
      ]
  }
}

Examples using optional predefined filters

  • Get all atoms in the AttentionalFocus
Uri: atoms?filterby=attentionalfocus
  • Get all atoms in the STI range between 5 (inclusive) and 10 (inclusive)
Uri: atoms?filterby=stirange&stimin=5&stimax=10
  • Get all atoms with STI greater than or equal to 5
Uri: atoms?filterby=stirange&stimin=5

POST

Creates a new atom. If the atom already exists, it updates the atom.

Uri: atoms

Include data with the POST request providing a JSON representation of the atom.

Valid data elements:

type (required) Atom type
see OpenCog_Atom_types
name (required for Node types, not allowed for Link types) Atom name
truthvalue (required) TruthValue, formatted as follows:
type (required) TruthValue type
(only 'simple' is currently available), see TruthValue
details (required) TruthValue parameters, formatted as follows:
strength (required)
count (required)
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

Example request:

Node

{
    'type': 'ConceptNode',
    'name': 'Frog',
    'truthvalue':
      {
        'type': 'simple',
        'details':
          {
            'strength': 0.8,
            'count': 0.2
          }
      }
}

Link

{
    'type': 'InheritanceLink',
    'outgoing': [1, 2],
    'truthvalue':
      {
        'type': 'simple',
        'details':
          {
            'strength': 0.5,
            'count': 0.4
          }
      }
}

Returns:

result JSON representation of an atom list containing the atom

Example response:

{
  'atoms':
  {
    'handle': 6,
    'name': '',
    'type': 'InheritanceLink',
    'outgoing': [2, 1],
    'incoming': [],
    'truthvalue':
      {
        'type': 'simple',
        'details':
          {
            'count': '0.4000000059604645',
            'confidence': '0.0004997501382604241',
            'strength': '0.5'
          }
      },
    'attentionvalue':
      {
        'lti': 0,
        'sti': 0,
        'vlti': false
      }
  }
}


PUT

Updates the AttentionValue (STI, LTI, VLTI) or TruthValue of an atom

Uri: atoms/[id]

Parameters:

id Atom handle

Include data with the PUT request providing a JSON representation of the updated attributes.

Valid data elements:

truthvalue (optional) TruthValue, formatted as follows:
type (required) TruthValue type
(only 'simple' is currently available), see TruthValue
details (required) TruthValue parameters, formatted as follows:
strength (required)
count (required)
attentionvalue (optional) AttentionValue, formatted as follows:
sti (optional) Short-Term Importance
lti (optional) Long-Term Importance
vlti (optional) Very-Long Term Importance

Example request:

{
  'truthvalue':
  {
    'type': 'simple',
    'details':
      {
        'strength': 0.005,
        'count': 0.8
      }
  },
'attentionvalue':
  {
    'sti': 9,
    'lti': 2,
    'vlti': True
  }
}

Returns:

atoms JSON representation of an atom list containing the atom.

Example response:

{ 'atoms':
  {
    'handle': 6,
    'name': '',
    'type': 'InheritanceLink',
    'outgoing': [2, 1],
    'incoming': [],
    'truthvalue':
      {
        'type': 'simple',
        'details':
          {
            'count': '0.4000000059604645',
            'confidence': '0.0004997501382604241',
            'strength': '0.5'
          }
      },
    'attentionvalue':
      {
        'lti': 0,
        'sti': 0,
        'vlti': false
      }
    }
  }
}

DELETE

Removes an atom from the AtomSpace

Uri: atoms/[id]

Parameters:

id Atom handle

Returns:

result JSON representation of the result, indicating success or failure

Example response:

{
  'result':
  {
    'handle': 2,
    'success': 'true'
  }
}

Types

Returns a list of valid atom types

Uri: types

{"types": ["TrueLink", "NumberNode", "OrLink", "PrepositionalRelationshipNode"]}

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 this file: https://github.com/opencog/opencog/blob/master/opencog/python/web/api/exampleclient.py

Development

The restapi.py file implements a CogServer Module to load upon startup that will load the REST API defined in 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 (http://www.w3.org/TR/cors/) 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.0/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