ReST

From OpenNMS
Jump to: navigation, search


Work In Progress

This article is a work in progress, and as a result may change without notice.

For more information on the current state of this page, ask user indigo or check the Jira ticket: NMS-7536

Last Revision: 13 October 2015 16:01

A RESTful interface is a web service conforming to the REST architectural style as described in the book RESTful Web Services. This page is describes the RESTful interface for OpenNMS.

Contents

ReST URL

The base URL for Rest Calls is : http://opennmsserver:8980/opennms/rest/

For instance, http://localhost:8980/opennms/rest/alarms/ will give you the current alarms in the system.

Authentication

Use HTTP Basic authentication to provide a valid username and password. By default you will not receive a challenge, so you must configure your ReST client library to send basic authentication proactively.

Data format

Jersey allows ReST calls to be made using either XML or JSON.

By default a request to the API is returned in XML. To get JSON encoded responses one has to send the following header with the request: "Accept: application/json".

Standard Params

The following are standard params which are available on most resources (noted below)

  • limit - integer, limiting the number of results. This is particularly handy on events and notifications, where an accidental call with no limit could result in many thousands of results being returned, killing either the client or the server. If set to 0, then no limit applied
  • offset - integer, being the numeric offset into the result set from which results should start being returned. E.g., if there are 100 result entries, offset is 15, and limit is 10, then entries 15-24 will be returned. Used for pagination
  • Filtering: All properties of the entity being accessed can be specified as parameters in either the URL (for GET) or the form value (for PUT and POST). If so, the value will be used to add a filter to the result. By default, the operation is equality, unless the "comparator" parameter is sent, in which case it applies to *all* comparisons in the filter. Multiple properties will result in an "AND" operation between the filter elements. Available comparators are:
    • eq Checks for equality
    • ne Checks for non-equality
    • ilike Case-insensitive wildcarding (% is the wildcard)
    • like Case-sensitive wildcarding (% is the wildcard)
    • gt Greater than
    • lt Less than
    • ge Greater than or equal
    • le Less than or equal

If the value "null" is passed for a given property, then the obvious operation will occur (comparator will be ignored for that property).
"notnull" is handled similarly.

  • Ordering: If the parameter "orderBy" is specified, results will be ordered by the named property. Default is ascending, unless the "order" parameter is set to "desc" (any other value will default to ascending)
  • Raw where clause: If there is a "query" parameter, it will be used as a raw where clause (SQL, not HQL), and added to any other filters created by other parameters

Standard filter examples

Take /events as an example.

/events?eventUei=uei.opennms.org/internal/rtc/subscribe would return the first 10 events with the rtc subscribe UEI, (10 being the default limit for events)
/events?eventUei=uei.opennms.org/internal/rtc/subscribe&limit=0 would return *all* the rtc subscribe events (potentially quite a few)
/events?id=100&comparator=gt would return the first 10 events with an id greater than 100
/events?eventAckTime=notnull would return the first 10 events that have a non-null Ack time (i.e. those that have been acknowledged)
/events?eventAckTime=notnull&id=100&comparator=gt&limit=20 would return the first 20 events that have a non-null Ack time and an id greater than 100. Note that the notnull value causes the comparator to be ignored for eventAckTime
/events?eventAckTime=2008-07-28T04:41:30.530%2B12:00&id=100&comparator=gt&limit=20 would return the first 20 events that have were acknowledged after 28th July 2008 at 4:41am (+12:00), and an id greater than 100. Note that the same comparator applies to both property comparisons. Also note that you must URL encode the plus sign when using GET.
/events?orderBy=id&order=desc would return the 10 latest events inserted (probably, unless you've been messing with the id's)

Currently Implemented Interfaces

Nodes

Note: the default offset is 0, the default limit is 10 results. To get all results, use limit=0 as a parameter on the URL (ie, GET /nodes?limit=0).

Additionally, anywhere you use "id" in the queries below, you can use the foreign source and foreign ID separated by a colon instead (ie, GET /nodes/fs:fid).

GETs (Reading Data)

/nodes Get a list of nodes. This includes the ID and node label.
/nodes/{id} Get a specific node, by ID.
/nodes/{id}/ipinterfaces Get the list of IP interfaces associated with the given node.
/nodes/{id}/ipinterfaces/{ipAddress} Get the IP interface for the given node and IP address.
/nodes/{id}/ipinterfaces/{ipAddress}/services Get the list of services associated with the given node and IP interface.
/nodes/{id}/ipinterfaces/{ipAddress}/services/{service} Get the requested service associated with the given node, IP interface, and service name.
/nodes/{id}/snmpinterfaces Get the list of SNMP interfaces associated with the given node.
/nodes/{id}/snmpinterfaces/{ifIndex} Get the specific interface associated with the given node and ifIndex.
/nodes/{id}/categories Get the list of categories associated with the given node.
/nodes/{id}/categories/{categoryName} Get the category associated with the given node and category name.
/nodes/{id}/assetRecord Get the asset record associated with the given node.

POSTs (Adding Data)

POST requires XML using application/xml as its Content-Type.

/nodes Add a node.
/nodes/{id}/ipinterfaces Add an IP interface to the node.
/nodes/{id}/ipinterfaces/{ipAddress}/services Add a service to the interface for the given node.
/nodes/{id}/snmpinterfaces Add an SNMP interface to the node.
/nodes/{id}/categories Add a category association to the node.

PUTs (Modifying Data)

PUT requires form data using application/x-www-form-urlencoded as a Content-Type.

/nodes/{id} Modify a node with the given ID.
/nodes/{id}/ipinterfaces/{ipAddress} Modify the IP interface with the given node ID and IP address.
/nodes/{id}/ipinterfaces/{ipAddress}/services/{service} Modify the service with the given node ID, IP address, and service name.
/nodes/{id}/snmpinterfaces/{ifIndex} Modify the SNMP interface with the given node ID and ifIndex.
/nodes/{id}/categories/{categoryName} Modify the category with the given node ID and name.

DELETEs (Removing Data)

Perform a DELETE to the singleton URLs specified in PUTs above to delete that object.

Example with provision.pl

This example will add TEST DESCRIPTION to a node's asset description field using ReST.

provision.pl asset add <requisition> <node foreignid> description "TEST DESCRIPTION"
provision.pl requisition import <requisition>

Events

GETs (Reading Data)

/events Get a list of events. The default for offset is 0, and the default for limit is 10. To get all results, use limit=0 as a parameter on the URL (ie, GET /events?limit=0).
/events/count Get the number of events. (Returns plaintext, rather than XML or JSON.)
/events/{id} Get the event specified by the given ID.

PUTs (Modifying Data)

PUT requires form data using application/x-www-form-urlencoded as a Content-Type.

/events/{id}?ack=(true;false) Acknowledges (or unacknowledges) an event.
/events?x=y&...&ack=(true;false) Acknowledges (or unacknowledges) the matching events.

Alarms

Note: the default offset is 0, the default limit is 10 results. To get all results, use limit=0 as a parameter on the URL (ie, GET /events?limit=0).

GETs (Reading Data)

/alarms Get a list of alarms.
/alarms/count Get the number of alarms. (Returns plaintext, rather than XML or JSON.)
/alarms/{id} Get the alarms specified by the given ID.

Note that you can also query by severity, like so:

/alarms?comparator=ge&severity=MINOR Get the alarms with a severity greater than or equal to "MINOR".

PUTs (Modifying Data)

PUT requires form data using application/x-www-form-urlencoded as a Content-Type.

/alarms/{id}?ack=(true;false) Acknowledges (or unacknowledges) an alarm.
/alarms?x=y&...&ack=(true;false) Acknowledges (or unacknowledges) alarms matching the additional query parameters. eg, /alarms?node.id=4&ack=true
New in OpenNMS 1.11.0

In OpenNMS 1.11.0, some additional features are supported in the alarm ack API:

/alarms/{id}?clear=true Clears an alarm.
/alarms/{id}?escalate=true Escalates an alarm. eg, NORMAL -> MINOR, MAJOR -> CRITICAL, etc.
/alarms?x=y&...&clear=true Clears alarms matching the additional query parameters.
/alarms?x=y&...&escalate=true Escalates alarms matching the additional query parameters.

Additionally, when acknowledging alarms (ack=true) you can now specify an ackUser parameter. You will only be allowed to ack as a different user IFF you are PUTting as an authenticated user who is in the "admin" role.

Queries

As noted above, it is possible to pass a raw "query" parameter when doing ReST queries. In the case of alarms, it is possible to pass severity names when querying by severity, rather than having to know the number that the severity enum maps to. For example:

 /alarms?query=lastEventTime%20%3E%20'2011-08-19T11%3A11%3A11.000-07%3A00'%20AND%20severity%20%3E%20MAJOR%20AND%20alarmAckUser%20IS%20NULL

This will get any alarms where the last event associated with the alarm is newer than August 19th, 2011 11:11:11, the severity is greater than MAJOR, and the alarm is not acknowledged (alarmAckUser is null).

You should be able to use any column in the alarm, event, node, ipinterface, or snmpinterface tables.

Acknowledgements

Note: the default offset is 0, the default limit is 10 results. To get all results, use limit=0 as a parameter on the URL (ie, GET /acks?limit=0).

GETs (Reading Data)

/acks Get a list of acknowledgements.
/acks/count Get the number of acknowledgements. (Returns plaintext, rather than XML or JSON.)
/acks/{id} Get the acknowledgement specified by the given ID.

POSTs (Setting Data)

/acks Creates or modifies an acknowledgement for the given alarm ID or notification ID. To affect an alarm, set an alarmId< parameter in the URL-encoded POST body; to affect a notification, set notifyId instead. An action parameter is also required, and may be one of ack, unack, clear, or esc (escalate).

Usage examples with curl

Acknowledge notification #3
curl -u 'admin:admin' -X POST -d notifId=3 -d action=ack http://localhost:8980/opennms/rest/acks
Escalate alarm #42
curl -u 'admin:admin' -X POST -d alarmId=42 -d action=esc http://localhost:8980/opennms/rest/acks

Notifications

Note: the default offset is 0, the default limit is 10 results. To get all results, use limit=0 as a parameter on the URL (ie, GET /events?limit=0).

GETs (Reading Data)

/notifications Get a list of notifications.
/notifications/count Get the number of notifications. (Returns plaintext, rather than XML or JSON.)
/notifications/{id} Get the notification specified by the given ID.

To acknowledge or unacknowledge a notification, use the acks endpoint -- see Acknowledgements

Outages

GETs (Reading Data)

/outages Get a list of outages.
/outages/count Get the number of outages. (Returns plaintext, rather than XML or JSON.)
/outages/{id} Get the outage specified by the given ID.
/outages/forNode/{nodeId} Get the outages that match the given node ID.

Scheduled Outages

(As of openNMS 1.10)

GETs (Reading Data)

/sched-outages to get a list of configured scheduled outages.
/sched-outages/{outageName} to get the details of a specific outage.

POSTs (Setting Data)

/sched-outages to add a new outage (or update an existing one).

PUTs (Modifying Data)

/sched-outages/{outageName}/collectd/{package} to add a specific outage to a collectd's package.
/sched-outages/{outageName}/pollerd/{package} to add a specific outage to a pollerd's package.
/sched-outages/{outageName}/threshd/{package} to add a specific outage to a threshd's package.
/sched-outages/{outageName}/notifd to add a specific outage to the notifications.

DELETEs (Removing Data)

/sched-outages/{outageName} to delete a specific outage.
/sched-outages/{outageName}/collectd/{package} to remove a specific outage from a collectd's package.
/sched-outages/{outageName}/pollerd/{package} to remove a specific outage from a pollerd's package.
/sched-outages/{outageName}/threshd/{package} to remove a specific outage from a threshd's package.
/sched-outages/{outageName}/notifd to remove a specific outage from the notifications.

Requisitions

RESTful service to the OpenNMS Provisioning Requisitions. In this API, these "groups" of nodes are aptly named and treated as requisitions.

This current implementation supports CRUD operations for managing provisioning requisitions. Requisitions are first POSTed and no provisioning (import/synchronize) operations are taken. This is done so that a) the XML can be verified and b) so that the operations can happen at a later time. They are moved to the deployed state (put in the active requisition repository) when an import is run.

If a request says that it gets the "active" requisition, that means it returns the pending requisition (being edited for deployment) if there is one, otherwise it returns the deployed requisition.

Note that anything that says it adds/deletes/modifies a "node," "interface," etc. in these instructions is referring to modifying that element from the requisition not from the database itself. That will happen upon import/synchronization.

You may write requisition data if the authenticated user is in the provision, rest, or admin roles.

GETs (Reading Data)

/requisitions Get all active requisitions.
/requisitions/count Get the number of active requisitions. (Returns plaintext, rather than XML or JSON.)
/requisitions/deployed Get the list of all deployed (active) requisitions.
/requisitions/deployed/count Get the number of deployed requisitions. (Returns plaintext, rather than XML or JSON.)
/requisitions/{name} Get the active requisition for the given foreign source name.
/requisitions/{name}/nodes Get the list of nodes being requisitioned for the given foreign source name.
/requisitions/{name}/nodes/{foreignId} Get the node with the given foreign ID for the given foreign source name.
/requisitions/{name}/nodes/{foreignId}/interfaces Get the interfaces for the node with the given foreign ID and foreign source name.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress} Get the interface with the given IP for the node with the specified foreign ID and foreign source name.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress}/services Get the services for the interface with the specified IP address, foreign ID, and foreign source name.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress}/services/{service} Get the given service with the specified IP address, foreign ID, and foreign source name.
/requisitions/{name}/nodes/{foreignId}/categories Get the categories for the node with the given foreign ID and foreign source name.
/requisitions/{name}/nodes/{foreignId}/categories/{categoryName} Get the category with the given name for the node with the specified foreign ID and foreign source name.
/requisitions/{name}/nodes/{foreignId}/assets Get the assets for the node with the given foreign ID and foreign source name.
/requisitions/{name}/nodes/{foreignId}/assets/{assetName} Get the value of the asset for the given assetName for the node with the given foreign ID and foreign source name.

POSTs (Adding Data)

/requisitions Adds (or replaces) a requisition.
/requisitions/{name}/nodes Adds (or replaces) a node in the specified requisition. This operation can be very helpful when working with Large Requisitions.
/requisitions/{name}/nodes/{foreignId}/interfaces Adds (or replaces) an interface for the given node in the specified requisition.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress}/services Adds (or replaces) a service on the given interface in the specified requisition.
/requisitions/{name}/nodes/{foreignId}/categories Adds (or replaces) a category for the given node in the specified requisition.
/requisitions/{name}/nodes/{foreignId}/assets Adds (or replaces) an asset for the given node in the specified requisition.

PUTs (Modifying Data)

/requisitions/{name}/import Performs an import/synchronize on the specified foreign source. This turns the "active" requisition into the "deployed" requisition.
/requisitions/{name}/import?rescanExisting=false Performs an import/synchronize on the specified foreign source. This turns the "active" requisition into the "deployed" requisition. Existing nodes will not be scanned until the next rescan interval, only newly-added nodes will be. Useful if you're planning on making a series of changes.
/requisitions/{name} Update the specified foreign source.
/requisitions/{name}/nodes/{foreignId} Update the specified node for the given foreign source.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress} Update the specified IP address for the given node and foreign source.

DELETEs (Removing Data)

/requisitions/{name} Delete the pending requisition for the named foreign source.
/requisitions/deployed/{name} Delete the active requisition for the named foreign source.
/requisitions/{name}/nodes/{foreignId} Delete the node with the given foreign ID from the given requisition.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress} Delete the IP address from the requisitioned node with the given foreign ID and foreign source.
/requisitions/{name}/nodes/{foreignId}/interfaces/{ipAddress}/services/{service} Delete the service from the requisitioned interface with the given IP address, foreign ID and foreign source.
/requisitions/{name}/nodes/{foreignId}/categories/{category} Delete the category from the node with the given foreign ID and foreign source.
/requisitions/{name}/nodes/{foreignId}/assets/{field} Delete the field from the requisition's nodes asset with the given foreign ID and foreign source.

Foreign Sources

ReSTful service to the OpenNMS Provisioning Foreign Source definitions. Foreign source definitions are used to control the scanning (service detection) of services for SLA monitoring as well as the data collection settings for physical interfaces (resources).

This API supports CRUD operations for managing the Provisioner's foreign source definitions. Foreign source definitions are POSTed and will be deployed when the corresponding requisition gets imported/synchronized by Provisiond.

If a request says that it gets the "active" foreign source, that means it returns the pending foreign source (being edited for deployment) if there is one, otherwise it returns the deployed foreign source.

GETs (Reading Data)

/foreignSources Get all active foreign sources.
/foreignSources/default Get the active default foreign source.
/foreignSources/deployed Get the list of all deployed (active) foreign sources.
/foreignSources/deployed/count Get the number of deployed foreign sources. (Returns plaintext, rather than XML or JSON.)
/foreignSources/{name} Get the active foreign source named {name}.
/foreignSources/{name}/detectors Get the configured detectors for the foreign source named {name}.
/foreignSources/{name}/detectors/{detector} Get the specified detector for the foreign source named {name}.
/foreignSources/{name}/policies Get the configured policies for the foreign source named {name}.
/foreignSources/{name}/policies/{policy} Get the specified policy for the foreign source named {name}.

POSTs (Adding Data)

POST requires XML using application/xml as its Content-Type.

/foreignSources Add a foreign source.
/foreignSources/{name}/detectors Add a detector to the named foreign source.
/foreignSources/{name}/policies Add a policy to the named foreign source.

PUTs (Modifying Data)

PUT requires form data using application/x-www-form-urlencoded as a Content-Type.

/foreignSources/{name} Modify a foreign source with the given name.

DELETEs (Removing Data)

/foreignSources/{name} Delete the named foreign source.
/foreignSources/{name}/detectors/{detector} Delete the specified detector from the named foreign source.
/foreignSources/{name}/policies/{policy} Delete the specified policy from the named foreign source.

SNMP Configuration

You can edit the community string, SNMP version, etc. for an IP address using this interface. If you make a change that would overlap with an existing snmp-config.xml, it will automatically create groups of <definition /> entries as necessary. If no <definition /> entry is created it matches the defaults.

There are different versions of the interface (see below). The following operations are supported:

GETs (Reading Data)

/snmpConfig/{ipAddress} Get the SNMP configuration for a given IP address.

PUTs (Modifying Data)

/snmpConfig/{ipAddress} Add or update the SNMP configuration for a given IP address.

Determine API version

To determine the version of the API running in your OpenNMS type http://localhost:8980/opennms/rest/snmpConfig/1.1.1.1 in your browser and have a look at the output:

  • Version 1: If the output only have attributes "community", "port", "retries", "timeout" and "version"
  • Version 2: If there are more attributes than described before (e.g. max Repetitions)

API Version 1

In version 1 only a few attributes defined in snmp-config.xsd are supported. These are defined in snmp-info.xsd:

<xs:schema 
    xmlns:tns="http://xmlns.opennms.org/xsd/config/snmp-info" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
    elementFormDefault="qualified" 
    version="1.0" 
    targetNamespace="http://xmlns.opennms.org/xsd/config/snmp-info">
  <xs:element name="snmp-info" type="tns:snmpInfo"/>
  <xs:complexType name="snmpInfo">
    <xs:sequence>
      <xs:element name="community" type="xs:string" minOccurs="0"/>
      <xs:element name="port" type="xs:int"/>
      <xs:element name="retries" type="xs:int"/>
      <xs:element name="timeout" type="xs:int"/>
      <xs:element name="version" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

The following table shows all supported attributes, optional restrictions and the mapping between snmp-info.xsd and snmp-config.xsd. All parameters can be set regardless the version.

attribute snmp-info.xml attribute snmp-config.xml default restricted to version restriction
version version v1 - "v1", "v2c" or "v3" are valid arguments. If an invalid or empty argument is provided "v1" is used.
port port 161 - Integer > 0
retries retry 1 - Integer > 0
timeout timeout 3000 - Integer > 0
community read-community public - any string with a length >= 1
Example 1 
curl -v -X PUT -H "Content-Type: application/xml" \
     -H "Accept: application/xml" \
     -d "&lt;snmp-info&gt;
             &lt;community&gt;yRuSonoZ&lt;/community&gt;
             &lt;port&gt;161&lt;/port&gt;
             &lt;retries&gt;1&lt;/retries&gt;
             &lt;timeout&gt;2000&lt;/timeout&gt;
             &lt;version&gt;v2c&lt;/version&gt;
          &lt;/snmp-info&gt;" \
     -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Creates or updates a <definition/>-entry for IP address 10.1.1.1 in snmp-config.xml.

Example 2 
curl -v -X GET -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Returns the SNMP configuration for IP address 10.1.1.1 as defined in example 1.

API Version 2

Since Version 2 all attributes of a <definition /> entry defined in snmp-config.xsd (http://xmlns.opennms.org/xsd/config/snmp) can be set or get via the interface - except it is only possible to set the configuration for one IP address and not for a range of IP addresses. This may change in the future.

The interface uses SnmpInfo objects for communication. Therefore it is possible to set for example v1 and v3 parameters in one request (e.g. readCommunity String and privProtocol String). However OpenNMS does not allow this. It is only allowed to set attributes which have no version restriction (e.g. timeout value) or the attributes which are limited to the version (e.g. readCommunity String if version is v1/v2c). The same is for getting data from the API, even if it is possible to store v1 and v3 parameters in one definition block in the snmp-config.xml manually, the REST API will only return the parameters which match the version. If no version is defined, the default is assumed (both in PUT and GET requests).

The SnmpInfo schema is defined as follows:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema 
  elementFormDefault="qualified"
  version="1.0" 
  targetNamespace="http://xmlns.opennms.org/xsd/config/snmp-info" 
  xmlns:tns="http://xmlns.opennms.org/xsd/config/snmp-info" 
  xmlns:xs="http://www.w3.org/2001/XMLSchema">
 
  <xs:element name="snmp-info" type="tns:snmpInfo"/>
  <xs:complexType name="snmpInfo">
    <xs:sequence>
      <xs:element name="authPassPhrase" type="xs:string" minOccurs="0"/>
      <xs:element name="authProtocol" type="xs:string" minOccurs="0"/>
      <xs:element name="community" type="xs:string" minOccurs="0"/>
      <xs:element name="contextEngineId" type="xs:string" minOccurs="0"/>
      <xs:element name="contextName" type="xs:string" minOccurs="0"/>
      <xs:element name="engineId" type="xs:string" minOccurs="0"/>
      <xs:element name="enterpriseId" type="xs:string" minOccurs="0"/>
      <xs:element name="maxRepetitions" type="xs:int" minOccurs="0"/>
      <xs:element name="maxRequestSize" type="xs:int" minOccurs="0"/>
      <xs:element name="maxVarsPerPdu" type="xs:int" minOccurs="0"/>
      <xs:element name="port" type="xs:int" minOccurs="0"/>
      <xs:element name="privPassPhrase" type="xs:string" minOccurs="0"/>
      <xs:element name="privProtocol" type="xs:string" minOccurs="0"/>
      <xs:element name="proxyHost" type="xs:string" minOccurs="0"/>
      <xs:element name="readCommunity" type="xs:string" minOccurs="0"/>
      <xs:element name="retries" type="xs:int" minOccurs="0"/>
      <xs:element name="securityLevel" type="xs:int" minOccurs="0"/>
      <xs:element name="securityName" type="xs:string" minOccurs="0"/>
      <xs:element name="timeout" type="xs:int" minOccurs="0"/>
      <xs:element name="version" type="xs:string" minOccurs="0"/>
      <xs:element name="writeCommunity" type="xs:string" minOccurs="0"/>
    </xs:sequence>
  </xs:complexType>
</xs:schema>

The following table shows all supported attributes, the mapping between snmp-info.xsd and snmp-config.xsd. It also shows the version limitations, default values and the restrictions - if any.

attribute snmp-info.xml attribute snmp-config.xml default restricted to version restriction
version version v1 - "v1", "v2c" or "v3" are valid arguments. If an invalid or empty argument is provided "v1" is used.
port port 161 - Integer > 0
retries retry 1 - Integer > 0
timeout timeout 3000 - Integer > 0
maxVarsPerPdu max-vars-per-pdu 10 - Integer > 0
maxRepetitions max-repetitions 2 - Integer > 0
maxRequestSize max-request-size 65535 - Integer > 0
proxyHost proxy-host -
readCommunity read-community public v1, v2c
writeCommunity write-community private v1, v2c
securityName security-name opennmsUser v3
securityLevel security-level noAuthNoPriv v3 Integer value, which can be null, 1, 2, or 3.
  • 1 means noAuthNoPriv
  • 2 means authNoPriv
  • 3 means authPriv
If you do not set the security level manually it is determined automatically:
  • if no authPassPhrase set the securityLevel is 1
  • if a authPassPhrase and no privPassPhrase is set the security level is 2.
  • if a authPassPhrase and a privPassPhrase is set the security level is 3.
authPassPhrase auth-passphrase 0p3nNMSv3 v3
authProtocol auth-protocol MD5 v3 only MD5 or SHA are valid arguments
privPassPhrase privacy-passphrase 0p3nNMSv3 v3
privProtocol privacy-protocol DES v3 only DES, AES, AES192 or AES256 are valid arguments.
engineId engine-id v3
contextEngineId context-engine-id v3
contextName context-name v3
enterpriseId enterprise-id v3
Example 1 
curl -v -X PUT -H "Content-Type: application/xml" \
     -H "Accept: application/xml" \
     -d "&lt;snmp-info&gt;
             &lt;readCommunity&gt;yRuSonoZ&lt;/readCommunity&gt;
             &lt;port&gt;161&lt;/port&gt;
             &lt;retries&gt;1&lt;/retries&gt;
             &lt;timeout&gt;2000&lt;/timeout&gt;
             &lt;version&gt;v2c&lt;/version&gt;
          &lt;/snmp-info&gt;" \
     -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Creates or updates a <definition/>-entry for IP address 10.1.1.1 in snmp-config.xml.

Example 2 
curl -v -X GET -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Returns the SNMP configuratoin for IP address 10.1.1.1 as defined in example 1.

Example 3 
curl -v -X PUT -H "Content-Type: application/xml" \
     -H "Accept: application/xml" \
     -d "&lt;snmp-info&gt;
             &lt;readCommunity&gt;yRuSonoZ&lt;/readCommunity&gt;
             &lt;port&gt;161&lt;/port&gt;
             &lt;retries&gt;1&lt;/retries&gt;
             &lt;timeout&gt;2000&lt;/timeout&gt;
             &lt;version&gt;v1&lt;/version&gt;
             &lt;securityName&gt;secret-stuff&lt;/securityName&gt;
             &lt;engineId&gt;engineId&lt;/engineId&gt;
          &lt;/snmp-info&gt;" \
     -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Creates or updates a <definition/>-entry for IP address 10.1.1.1 in snmp-config.xml ignoring attributes "securityName" and "engineId".

Example 4 
curl -v -X PUT -H "Content-Type: application/xml" \
     -H "Accept: application/xml" \
     -d "&lt;snmp-info&gt;
             &lt;readCommunity&gt;yRuSonoZ&lt;/readCommunity&gt;
             &lt;port&gt;161&lt;/port&gt;
             &lt;retries&gt;1&lt;/retries&gt;
             &lt;timeout&gt;2000&lt;/timeout&gt;
             &lt;version&gt;v3&lt;/version&gt;
             &lt;securityName&gt;secret-stuff&lt;/securityName&gt;
             &lt;engineId&gt;engineId&lt;/engineId&gt;
          &lt;/snmp-info&gt;" \
     -u admin:admin http://localhost:8980/opennms/rest/snmpConfig/10.1.1.1

Creates or updates a <definition/>-entry for IP address 10.1.1.1 in snmp-config.xml ignoring attribute "readCommunity".

Maps

The SVG maps use ReST to populate their data. This is the interface for doing that.

GETs (Reading Data)

/maps Get the list of maps.
/maps/{id} Get the map with the given ID.
/maps/{id}/mapElements Get the elements (nodes, links, etc.) for the map with the given ID.

POSTs (Adding Data)

/maps Add a map.

PUTs (Modifying Data)

/maps/{id} Update the properties of the map with the given ID.

DELETEs (Removing Data)

/maps/{id} Delete the map with the given ID.

Users

Since users are not currently stored in the database, the ReST interface for them is not as full-fledged as that of nodes, etc. (You cannot use hibernate criteria for filtering, for example.) You may need to touch the $OPENNMS_HOME/etc/users.xml file on the filesystem for any addition or modification actions to take effect (see NMS-6469 for details).

GETs (Reading Data)

/users Get a list of users.
/users/{username} Get a specific user, by username.

POSTs (Adding Data)

/users Add a user. If supplying a password it is assumed to be hashed or encrypted already, at least as of 1.12.5. To indicate that the supplied password uses the salted encryption algorithm rather than the older MD5 based algorithm, you need to pass an element named 'passwordSalt' with text 'true' after the password element (or key/value pairs if using JSON).

PUTs (Modifying Data)

/users/{username} Update an existing user's full-name, user-comments, password, passwordSalt and duty-schedule values.

Groups

(New in OpenNMS 1.9.94.)

Like users, groups have a simplified interface as well.

GETs (Reading Data)

/groups Get a list of groups.
/groups/{groupname} Get a specific group, given a group name.
/groups/{groupname}/users Get the users for a group, given a group name. (new in OpenNMS 14)
/groups/{groupname}/categories Get the categories associated with a group, given a group name. (new in OpenNMS 14)

POSTs (Adding Data)

/groups Add a new group.

PUTs (Modifying Data)

/groups/{groupname} Update the metadata of a group (eg, change the "comments" field).
/groups/{groupname}/users/{username} Add a user to the group, given a group name and username. (new in OpenNMS 14)
/groups/{groupname}/categories/{categoryname} Associate a category with the group, given a group name and category name. (new in OpenNMS 14)

DELETEs (Removing Data)

/groups/{groupname} Delete a group.
/groups/{groupname}/users/{username} Remove a user from the group. (new in OpenNMS 14)
/groups/{groupname}/categories/{categoryname} Disassociate a category from a group, given a group name and category name. (new in OpenNMS 14)

Alarm Statistics

(New in OpenNMS 1.9.94.)

It is possible to get some basic statistics on alarms, including the number of acknowledged alarms, total alarms, and the newest and oldest of acknowledged and unacknowledged alarms.

GETs (Reading Data)

/stats/alarms Returns statistics related to alarms. Accepts the same Hibernate parameters that you can pass to the /alarms ReST service.
/stats/alarms/by-severity Returns the statistics related to alarms, one per severity. You can optionally pass a list of severities to the "severities" query parameter to limit it to the specified severities. (eg, GET /opennms/rest/stats/alarms/by-severity?severities=MAJOR,CRITICAL).

Links

(New in OpenNMS 1.11)

You can manipulate raw Linkd DataLinkInterface information using the links API.

GETs (Reading Data)

/links Get a list of links. The default for offset is 0, and the default for limit is 10. To get all results, use limit=0 as a parameter on the URL (ie, GET /links?limit=0).
/links/{id} Get a link specifically by ID.

PUTs (Modifying Data)

PUT requires form data using application/x-www-form-urlencoded as a Content-Type.

/links/{id} Modify an existing link.

POSTs (Creating Data)

/links Add a new link.

DELETEs (Removing Data)

/links/{id} Delete the link with the given ID.

KSC Reports

GETs (Reading Data)

/ksc Get a list of all KSC reports, this includes ID and label.
/ksc/{reportId} Get a specific KSC report, by ID.
/ksc/count Get a count of all KSC reports.

PUTs (Modifying Data)

/ksc/{reportId} Modify a report with the given ID.

POSTs (Creating Data)

Documentation incomplete see issue: NMS-7162

DELETEs (Removing Data)

Documentation incomplete see issue: NMS-7162

Outage Timelines

GETs (Reading Data)

/header/{start}/{end}/{width} Generate the timeline header
/image/{nodeId}/{ipAddress}/{serviceName}/{start}/{end}/{width} Generate the timeline image
/empty/{start}/{end}/{width} Generate an empty timeline for non-monitored services
/html/{nodeId}/{ipAddress}/{serviceName}/{start}/{end}/{width} Generate the raw HTML for the image

Measurements API

(New in 16.0.0)

The Measurements API can be used to retrieve collected values stored in RRD (or JRB) files.

Note that all units of time are expressed in milliseconds.

GETs (Reading Data)

/measurements/{resourceId}/{attribute} Retrieve the measurements for a single attribute

The following table shows all supported query string parameters and their default values.

name default comment
start -14400000 Timestamp in milliseconds. If < 0, the effective value will be (end + start).
end 0 Timestamp in milliseconds. If <= 0, the effective value will be the current timestamp.
step 300000 Requested time interval between rows. Actual step may differ. Set to 1 for maximum accuracy.
maxrows 0 When using the measurements to render a graph, this should be set to the graph's pixel width.
aggregation AVERAGE Consolidation function used. Can typically be AVERAGE, MIN or MAX. Depends on RRA definitions.

Usage examples with curl

Retrieve CPU counter metrics over the last 2 hours for node 1
curl -u admin:admin "http://127.0.0.1:8980/opennms/rest/measurements/node%5B1%5D.nodeSnmp%5B%5D/CpuRawUser?start=-7200000&maxrows=30&aggregation=AVERAGE"
Response
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<query-response end="1425588138256" start="1425580938256" step="300000">
  <columns>
    <values>159.5957271523179</values>
    <values>158.08531037527592</values>
    <values>158.45835584842285</values>
    ...
  </columns>
  <labels>CpuRawUser</labels>
  <timestamps>1425581100000</timestamps>
  <timestamps>1425581400000</timestamps>
  <timestamps>1425581700000</timestamps>
  ...
</query-response>

POSTs (Reading Data)

/measurements Retrieve the measurements for one or more attributes, possibly spanning multiple resources, with support for JEXL expressions.

Here we use a POST instead of a GET to retrieve the measurements, which allows us to perform complex queries which are difficult to express in a query string. These requests cannot be used to update or create new metrics.

An example of the POST body is available bellow.

Usage examples with curl

Retrieve bits in and bits out metrics for a particular interface. Perform calculations on bits out, and only return the derived values.
curl -X POST  -H "Accept: application/json" -H "Content-Type: application/json" -u admin:admin  -d @report.json  http://127.0.0.1:8980/opennms/rest/measurements
Contents of report.json
{
    "start": 1425563626316,
    "end": 1425585226316,
    "step": 10000,
    "maxrows": 1600,
    "source": [
        {
            "aggregation": "AVERAGE",
            "attribute": "ifHCInOctets",
            "label": "ifHCInOctets",
            "resourceId": "nodeSource[NODES:1424038123222].interfaceSnmp[eth0-04013f75f101]",
            "transient": "false"
        },
        {
            "aggregation": "AVERAGE",
            "attribute": "ifHCOutOctets",
            "label": "ifHCOutOctets",
            "resourceId": "nodeSource[NODES:1424038123222].interfaceSnmp[eth0-04013f75f101]",
            "transient": "true"
        }
    ],
    "expression": [
        {
            "label": "ifHCOutOctetsNeg",
            "value": "-1.0 * ifHCOutOctets",
            "transient": "false"
        }
    ]
}
Response
{
    "step": 300000,
    "start": 1425563626316,
    "end": 1425585226316,
    "timestamps": [
        1425563700000,
        1425564000000,
        1425564300000,
        ...
    ],
    "labels": [
        "ifHCInOctets",
        "ifHCOutOctetsNeg"
    ],
    "columns": [
        {
            "values": [
                139.94817275747508,
                199.0062569213732,
                162.6264894795127,
                ...
            ]
        },
        {
            "values": [
                -151.66179401993355,
                -214.7415503875969,
                -184.9012624584718,
                ...
            ]
        }
    ]
}

Getting Graph data

While graphs aren't technically available via REST, you can parse some REST variables to get enough data to pull a graph. This isn't ideal because it requires multiple fetches, but depending on your use case, this may be adequate for you.

I'm in-lining some sample PHP code which should do this (not tested at all, cut & paste from old code I have that does not use the REST interface, and/or coded straight into the browser so YMMV).

If you go to your NMS and click the resource graphs, then right click the graph you want and hit "View Image" you will get the full URL that would need to be passed to pull that graph as a standalone image.

From that just take the URL and plug in the values you pulled from REST to get a graph for whatever node you wanted.

function fetchit($thing, $user = "user", $pass = "pass") {
    $url = "http://localhost:8980/opennms";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . $thing);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_USERPWD, $user.':'.$pass);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

// this assumes you already have found the nodeId via a previous REST call or some other means.  Provided more as an example than what you might want.
function getNodeInterfaces($nodeId) {
    $data = fetchit("/rest/nodes/$nodeId/snmpinterfaces");
     return simplexml_load_string($data);
}

function fetchGraphs($nodeId) {
     $ints = getNodeInterfaces($nodeId);
     $chars = array('/','.',':','-',' ');
     $endtime = time();
     $starttime = (string)(time() - ($days * 24 * 60 * 60)) ;
     
     // use bcmath or a better version of PHP if  you don't want this hypocrisy here.
     $endtime = $endtime . '000';
     $starttime = $starttime . '000';

     for($i=0; $i<count($ints->snmpInterfaces); $i++) {
         $ifname = $ints->snmpInterfaces[$i]->snmpInterface->ifName;
         $mac = $ints->snmpInterfaces[$i]->snmpInterface->physAddr;
         $if = str_replace($chars, "_", $ifname);
         if ( strlen(trim($mac)) < 12 ) { $mac_and_if = $if; } else { $mac_and_if = $if .'-'. $mac; };

         $image = fetchit("$url/graph/graph.png?resource=node[$nodeId].interfaceSnmp[$mac_and_if]&report=report=mib2.HCbits&start=$starttime&end=$endtime");
         // you can poop this to a file now, or set header('Content-type: image/png'); then print "$image";
     }
}

provision.pl examples and notes

One way to test out the new REST interface is to use provision.pl. If you run it you'll get a summary of the output, but it's not totally obvious how it all works.

Here is an example of adding a new node using the REST interface:

# add a new foreign source called ubr
/usr/share/opennms/bin/provision.pl requisition add ubr
/usr/share/opennms/bin/provision.pl node add ubr 10341111 clownbox
/usr/share/opennms/bin/provision.pl node set ubr 10341111 city clownville
/usr/share/opennms/bin/provision.pl node set ubr 10341111 building clown-town-hall
/usr/share/opennms/bin/provision.pl node set ubr 10341111 parent-foreign-id 1122114
/usr/share/opennms/bin/provision.pl interface add ubr 10341111 10.1.3.4
# this is like a commit.  No changes will take effect until you import a foreign source
/usr/share/opennms/bin/provision.pl requisition import ubr

You will probably need to specify the username/password of an admin. To do this add:

--username=admin --password=clownnms 

to the command line.

Debian (Lenny) Notes

For Lenny, you'll need to pull a package out of backports to make everything work right. Read http://backports.org/dokuwiki/doku.php?id=instructions for instructions on adding it to sources.list

# install liburi-perl from backports
sudo apt-get -t lenny-backports install liburi-perl

Windows Powershell REST

Example of using Windows Powershell to fill some asset fields with REST.

# Installdate of Windows
$wmi = Get-WmiObject -Class Win32_OperatingSystem
$dateInstalled = $wmi.ConvertToDateTime($wmi.InstallDate)

# Serialnumber and manufacturer of server
Get-WmiObject win32_bios | select SerialNumber
$wmi = Get-WmiObject -Class win32_bios 
$manufacturer = $wmi.Manufacturer

# Text file with a description of the server for the comments field
$comment = Get-Content "C:\Program Files\BGInfo\Info_Description.txt" | Out-String

$user ="admin"
$pass= "admin"

$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($pass, $secpasswd)

$nodeid = Invoke-RestMethod -Uri http://opennms.domain.nl:8980/opennms/rest/nodes?label=servername.domain.nl -Credential $cred
$nodeid = $nodeid.nodes.node.id

$uri="http://opennms.domain.nl:8980/opennms/rest/nodes/$nodeid/assetRecord"

Invoke-RestMethod -Uri "http://opennms.massxess.nl:8980/opennms/rest/nodes/$nodeid/assetRecord/?building=133" -Credential $cred -Method PUT
Invoke-RestMethod -Uri "$uri/?manufacturer=$manufacturer" -Credential $cred -Method PUT 
Invoke-RestMethod -Uri "$uri/?dateInstalled=$dateInstalled" -Credential $cred -Method PUT
Invoke-RestMethod -Uri "$uri/?comment=$comment" -Credential $cred -Method PUT