© 2015 X2Engine Inc.

Difference between revisions of "REST API Reference"

From X2Engine
Jump to: navigation, search
(Authenticating)
(Authentication)
Line 24: Line 24:
 
and a GET request to that URI would elicit a response from the server whose body contains a JSON-encoded list of attributes.
 
and a GET request to that URI would elicit a response from the server whose body contains a JSON-encoded list of attributes.
  
== Authentication ==
+
== Access Credentials ==
 
To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module  administrator. Any user can authenticate via the API by visiting the ''Update'' page for any given user.
 
To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module  administrator. Any user can authenticate via the API by visiting the ''Update'' page for any given user.
  

Revision as of 20:43, 2 May 2014

X2Engine's second-generation HTTP-based API, available as of version 4.1, is (for the most part) REST-ful, and includes many improvements over the original API.

This article is currently a work in progress.

Introduction

This API within X2Engine, can be accessed via the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2

It also:

  • Exclusively uses JSON for data input and output
  • Tends to use similar URIs for both input and output (distinguishing operations via the request method)
  • Uses a variety of server response codes to distinguish error scenarios in the case of an unsuccessful transaction
  • Uses the "HTTP Basic Auth" method for authentication

For example, to create a contact, one would send a POST request with its body a JSON-encoded attributes list to the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root

 index.php/api2/Contacts

with the Content-Type header set to application/json, and the request body as (for example):

{"firstName":"John","lastName":"Smith","visibility":1,"email":"johnsmith@example.com"}

If creation of the contact is successful, the server should respond with status code 201 ("Created"), and the response should contain a Location header with the full URL (including protocol) of the newly created contact (in addition to all the attributes of the new contact). If for example the new contact's ID is 123, that URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root would be

 index.php/api2/Contacts/123.json

and a GET request to that URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root would elicit a response from the server whose body contains a JSON-encoded list of attributes.

Access Credentials

To use the API, you will need to obtain X2Engine API credentials, which include a username and an API key. An X2Engine user with administrative privileges can get or set API keys in the Users module administrator. Any user can authenticate via the API by visiting the Update page for any given user.

Explore the API Using Your Web Browser

Once you have API credentials, you can examine the web API using your web browser by making GET requests to locations within index.php/api2 (simply by typing them into your browser's location bar). You can get a nicer view of the data returned by the server by installing a JSON viewing plugin in your web browser. A recommended plugin for this purpose is JSONView, which is available for Firefox and for Google Chrome (it's an unofficial port, but the developer of the API and author of this article uses it).

Example 1: hello, world

Try visiting the following URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root within X2Engine:

 index.php/api2/appInfo.json

Initially you will be prompted to enter the username and password to complete authentication; enter the API key corresponding to the user in the password field. The above URL should respond with a JSON string containing some basic info about the X2Engine application.

Example 2: direct access

You can get the ID of any given account record by going to it inside X2Engine as you normally would and examining the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. It should generally look something like this:

 index.php/accounts/32

or:

 index.php/accounts/id/32

In both of the above examples, the primary key value (id) of the record in question is 32. To view it in the API:

 index.php/api2/Accounts/32.json

Note how in the API, the first letter of "Accounts" is capitalized. This is because active record data in the API is accessed not via specifying the module containing the active record class, or to which the class corresponds, but by specifying the actual class name to use when accessing (or querying) data.

Example 3: querying

 index.php/api2/Actions?_order=-id&_limit=3

This will show you the last 3 action records (i.e. emails, call logs, to-do's) created in the system (which the current acting API user has permission to view), in descending order of their primary key values (column "id"). If you have no action records in your system, you should receive an empty array.

Prerequisites for API Applications

When writing an application to interface with X2Engine via the API, it is required or highly recommended that your language/coding environment of choice:

  • Have a JSON parsing and encoding library available
  • Have a library for making HTTP requests which can:
    • Set request headers
    • Parse response headers and read the response status code
    • Natively support requests using HTTP Basic Auth for access
    • Read responses even when the response code is not in the "success" category (2xx)
    • Make POST, PATCH/PUT and DELETE requests
  • Can access the network

Many high-level languages, such as Perl, PHP, Python and Ruby, meet these requirements. The specific usage of these languages is beyond the scope of this article; you will need to refer to the documentation of the library/libraries in use.

It is expected in the near future that a growing number of official API access classes (each in a different programming language) will be available for quick and easy development of API applications.

Interpreting Server Responses

HTTP Response Codes

It is important to be able to read and interpret status codes (and for that matter, response headers) because in all success scenarios, the API does not respond with data envelopes. By this it is meant the act of wrapping a data model's attributes inside another array containing metadata about the status of the request. This is in effort to streamline and make more elegant code that handles response data. It is also for consistency's sake. A contacts model accessed as a resource object with name ending with .json is expected to be that contact, and not rather an array with server response info or other metadata.

In general, the meanings of response codes closely or exactly follow the formal definitions as defined in RFC2616, as well as the informal definitions of unconventional status codes (See wikipedia:List of HTTP status codes). The following table lists each of the possible status codes that the API will respond with, the contexts in which they would appear, and what they indicate.

Code Request type or usage scenario Meaning
Success (2XX)
200 GET, PATCH, PUT and when adding tags via POST OK. General success status
201 POST Created. A record was created; see the value of the Location response header for its URL in the API
204 DELETE No content. An action was completed but the server does not need to return any content.
Redirection (3XX)
303 GET, when requesting a relationship record that is not actually associated with the current model See other. The requested resource is somewhere else. The Location header should contain the correct URL to the record.
Client Error (4XX)
400 All request methods/actions Invalid request. General status code for when something is missing, malformed or incorrect in the request headers/body.
401 All request methods/actions. Authentication failure or missing authentication credentials.
403 All request methods/actions. Forbidden. This may be because the user in API authentication does not actually have permission in X2Engine to perform the specified action (i.e. updating/viewing a particular record). In Platinum Edition, this code can also indicate that the IP address of the API client has been blocked.
404 All request methods/actions. Not found, or invalid URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root. It is used whenever a specified record to retrieve directly does not exist, but also as a catch-all for a location that the API was not configured to interpret.
405 All request methods/actions Method not allowed. The URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root is not malformed, but the method of the request being sent to the server is not permitted. An example would be sending a POST request, which is intended for creating new records, to the URI[[wikipedia:Uniform Resource Identifier]]: The part of a URL that identifies the resource on the server to be accessed. In the context of the API, this refers to the relative path within the web server based in the web root of X2Engine, i.e. ''index.php/api2/Contacts/324.json'' as opposed to the full URL, which begins with the protocol (i.e. "http") and might also contain a path relative to the web site's document root of an existing record, or sending a DELETE/POST/PUT request to a "read-only" resource.
408 All methods; server-generated Request timeout. This code is not as of this writing not produced by the API; it might be returned by the web server itself.
413 All methods; server-generated Request entity too large. This code is not as of this writing not produced by the API; it might be returned by the web server itself.
415 PATCH, POST, PUT Unsupported media type. As of this writing, this happens only whenever the request is sent with a body and the Content-Type header is not set to "application/json"
422 PATCH, POST, and PUT to create or update a record Unprocessable entity. This always indicates a validation error when attempting to set fields of and save an active record model.
429 Platinum Edition only; All request methods/actions Too many requests. When rate limiting is enabled in the API settings, the server will use this code to indicate that the API client has been making requests to the API too frequently. When this status is sent, the response should also contain a Retry-After header specifying the number of seconds to wait before trying again.
Server Error (5XX)
500 All request methods/actions Internal server error. General status for when something isn't right on the server. PHP and database errors will produce this status code.
501 All request methods/actions Not implemented. The API should use this code to denote that a given method, action, etc. is not yet available, but may be in the future.
503 Professional and Platinum Editions; All request methods/actions Unavailable. X2Engine and/or its API service has been disabled/locked by an administrator.

Error Stubs

In most error responses produced by the server, the API will also include in the body of the response a JSON with metadata about the response. This is for compatibility with less-than-satisfactory client libraries which cannot read the actual response code or headers, but might be able to read the response body when the code is not in the success (2XX) range. In such cases, the response will be a JSON-encoded object with at least the following properties:

property contents
httpHeaders A dictionary of HTTP headers that were set in the response.
message A general message about what happened and why. This will in most cases also be saved in the API log.
error Boolean true/false if an error occurred.
status The HTTP status code that was sent in the response header