Difference between revisions of "Rest API"

From Rackspace Email & Apps API
Jump to: navigation, search
m
Line 1: Line 1:
[[PageOutline]]
 
 
== Control Panel Email API ==
 
 
 
The Email API is a RESTful web service based on the Hypertext Transfer Protocol (HTTP). Actions and data requests are performed by using HTTP based commands. For more information on RESTful web services try the following sites:
 
The Email API is a RESTful web service based on the Hypertext Transfer Protocol (HTTP). Actions and data requests are performed by using HTTP based commands. For more information on RESTful web services try the following sites:
  
Line 9: Line 5:
 
http://java.sun.com/developer/technicalArticles/WebServices/restful/
 
http://java.sun.com/developer/technicalArticles/WebServices/restful/
  
=== Resources ===
+
== Resources ==
  
 
The following sections detail the operations that the API supports. The operations are grouped into sections based on the entity/object types that each operation interacts with.
 
The following sections detail the operations that the API supports. The operations are grouped into sections based on the entity/object types that each operation interacts with.
Line 34: Line 30:
  
  
=== Authentication ===
+
== Authentication ==
  
 
To gain access to the API, you must have keys generated from the Control Panel Web interface. These keys will be used to sign your request. The two keys are:
 
To gain access to the API, you must have keys generated from the Control Panel Web interface. These keys will be used to sign your request. The two keys are:
Line 73: Line 69:
 
An unsuccessful authentication will result in a 403 HTTP code.
 
An unsuccessful authentication will result in a 403 HTTP code.
  
==== X-Api-Signature Header ====
+
=== X-Api-Signature Header ===
  
 
Format is as follows:
 
Format is as follows:
Line 126: Line 122:
 
Be sure to encode the binary hash, not the hex hash, into base-64. The resulting string should be 28 characters long.
 
Be sure to encode the binary hash, not the hex hash, into base-64. The resulting string should be 28 characters long.
  
=== Throttling ===
+
== Throttling ==
  
 
The server limits the number of requests allowed per user in a certain period of time.  The current limit is 2500 requests over 5 minutes. The number of requests made are logged per minute. Calls that were made correctly with a user's API key, but not completed for any reason, including those exceeding the throttle limit, are included in this count.
 
The server limits the number of requests allowed per user in a certain period of time.  The current limit is 2500 requests over 5 minutes. The number of requests made are logged per minute. Calls that were made correctly with a user's API key, but not completed for any reason, including those exceeding the throttle limit, are included in this count.
Line 132: Line 128:
 
If a user is over the throttling limit then a 403 HTTP code will be returned with an "Exceeded request limits" message.
 
If a user is over the throttling limit then a 403 HTTP code will be returned with an "Exceeded request limits" message.
  
=== Formats ===
+
== Formats ==
  
 
The Email API supports two different response formats, XML and JSON. The response format is determined by HTTP 'Accept' header.
 
The Email API supports two different response formats, XML and JSON. The response format is determined by HTTP 'Accept' header.
Line 140: Line 136:
 
For JSON, populate the header with 'application/json' (ex: Headers!["Accept"] = "application/json").
 
For JSON, populate the header with 'application/json' (ex: Headers!["Accept"] = "application/json").
  
=== Versions ===
+
== Versions ==
  
 
The API version number is a component of the URL that is used to access the API. For example, to access the root of the API, the URL is http://api.emailsrvr.com/v1/. Bug fixes and minor non-breaking changes will be made without changing the version number. When major features or breaking changes are introduced, the version number will be incremented. It is not yet determined how many versions are going to be supported at any one time.
 
The API version number is a component of the URL that is used to access the API. For example, to access the root of the API, the URL is http://api.emailsrvr.com/v1/. Bug fixes and minor non-breaking changes will be made without changing the version number. When major features or breaking changes are introduced, the version number will be incremented. It is not yet determined how many versions are going to be supported at any one time.
  
Note: Pre-release versions of the API will be located at http://api.emailsrvr.com.com/v0/.
+
Note: Pre-release versions of the API will be located at http://api.emailsrvr.com/v0/.
  
 
{| border=1 class="simple"
 
{| border=1 class="simple"
Line 185: Line 181:
  
  
=== Filter/Search ===
+
== Filter/Search ==
  
 
The results of Index actions can be filtered/searched. The index URLs can take either one of the query strings: "?startswith==xxx" or "?contains==xxx," where "xxx" is the key word. If the request specifies more than one of these two query strings, a 400 HTTP error will be returned. Different fields will be searched depending on the resource type, see below.
 
The results of Index actions can be filtered/searched. The index URLs can take either one of the query strings: "?startswith==xxx" or "?contains==xxx," where "xxx" is the key word. If the request specifies more than one of these two query strings, a 400 HTTP error will be returned. Different fields will be searched depending on the resource type, see below.
Line 219: Line 215:
 
For the customer object only, the query string "referenceNumber=xxx" searches for a customer with an exact reference number. The result if found is the detail page of the customer.
 
For the customer object only, the query string "referenceNumber=xxx" searches for a customer with an exact reference number. The result if found is the detail page of the customer.
  
=== Examples ===
+
== Examples ==
  
==== Ruby ====
+
=== Ruby ===
  
 
This examples is written in [http://www.ruby-lang.org/en/ Ruby]. To make the examples shorter, helper methods have been written. These methods are part of a NetMethods module. The contents of the NetMethods module is listed below.
 
This examples is written in [http://www.ruby-lang.org/en/ Ruby]. To make the examples shorter, helper methods have been written. These methods are part of a NetMethods module. The contents of the NetMethods module is listed below.
Line 285: Line 281:
  
  
==== C# ====
+
=== C# ===
  
 
This examples is written in [http://msdn.microsoft.com/en-us/vcsharp/default.aspx C#].
 
This examples is written in [http://msdn.microsoft.com/en-us/vcsharp/default.aspx C#].
Line 366: Line 362:
 
</pre>
 
</pre>
  
==== PHP ====
+
=== PHP ===
  
 
<pre>
 
<pre>

Revision as of 14:54, 25 August 2009

The Email API is a RESTful web service based on the Hypertext Transfer Protocol (HTTP). Actions and data requests are performed by using HTTP based commands. For more information on RESTful web services try the following sites:

http://en.wikipedia.org/wiki/Representational_State_Transfer

http://java.sun.com/developer/technicalArticles/WebServices/restful/

Resources

The following sections detail the operations that the API supports. The operations are grouped into sections based on the entity/object types that each operation interacts with.

Resource Example URI
Customer /customers/123456789
Domain /customers/123456789/domains/example.com
Mailbox /customers/123456789/domains/example.com/ex/mailboxes/john.smith
Distribution List /customers/123456789/domains/example.com/ex/distributionlists/group.name
Contact /customers/123456789/domains/example.com/ex/contacts/john.smith


Authentication

To gain access to the API, you must have keys generated from the Control Panel Web interface. These keys will be used to sign your request. The two keys are:

Key Name Description Example
User Key A public key that corresponds to your admin id eGbq9/2hcZsRlr1JV1Pi
Secret Key A shared secret key QHOvchm/40czXhJ1OxfxK7jDHr3t



Requests to the API must then include HTTP headers with the following information:

Header Name Description Example
User-Agent An identifier you choose to identify your client software with Rackspace Management Interface
X-Api-Signature A string ending with a signature constructed as specified below eGbq9/2hcZsRlr1JV1Pi:20010317143725:HKUn0aajpSDx7qqGK3vqzn3FglI=


An unsuccessful authentication will result in a 403 HTTP code.

X-Api-Signature Header

Format is as follows:

<User Key>:<Timestamp>:<Signature>

Example: eGbq9/2hcZsRlr1JV1Pi:20010317143725:HKUn0aajpSDx7qqGK3vqzn3FglI=


User Key:
This is the public key issued by the Control Panel interface.


Timestamp:
The format is YYYYMMDDHHmmssff. All values besides year are zero-padded to two spaces. For example, March 17th 2001 at 2:37.25pm would be 20010317143725.

YYYY Four-digit year
MM Month
DD Day
HH Hour in 24h format
mm Minute
ss Second
ff Millisecond



Signature:

A SHA1 (Secure Hash Algorithm) hash must be applied to a string with the following information:

<User Key><User Agent><Timestamp><Secret Key>

Using the above example data, the string before hashing is:
eGbq9/2hcZsRlr1JV1PiRackspace Management Interface20010317143725QHOvchm/40czXhJ1OxfxK7jDHr3t

Resulting base-64 SHA1 Hash:
HKUn0aajpSDx7qqGK3vqzn3FglI=

Be sure to encode the binary hash, not the hex hash, into base-64. The resulting string should be 28 characters long.

Throttling

The server limits the number of requests allowed per user in a certain period of time. The current limit is 2500 requests over 5 minutes. The number of requests made are logged per minute. Calls that were made correctly with a user's API key, but not completed for any reason, including those exceeding the throttle limit, are included in this count.

If a user is over the throttling limit then a 403 HTTP code will be returned with an "Exceeded request limits" message.

Formats

The Email API supports two different response formats, XML and JSON. The response format is determined by HTTP 'Accept' header.

For XML, populate the header with 'text/xml' (ex: Headers!["Accept"] = "text/xml"). The XML document returned will conform to a published XSD (XML Schema Document).

For JSON, populate the header with 'application/json' (ex: Headers!["Accept"] = "application/json").

Versions

The API version number is a component of the URL that is used to access the API. For example, to access the root of the API, the URL is http://api.emailsrvr.com/v1/. Bug fixes and minor non-breaking changes will be made without changing the version number. When major features or breaking changes are introduced, the version number will be incremented. It is not yet determined how many versions are going to be supported at any one time.

Note: Pre-release versions of the API will be located at http://api.emailsrvr.com/v0/.

Non-breaking Changes Breaking Changes
Adding new fields or attributes to form fields sent Changing or deleting any fields in form fields sent
Adding fields in returned data Changing or removing fields in returned data
Changing the URI of any resource


The version number has been omitted from URLs in this documentation.

Paging

The results of Index actions are split into pages to lessen potentially high resource usage. The index URLs have a query string with parameters in the format "?size=xx&offset=xx." If a query parameter is omitted, the default value is used.

Query Parameter Default Maximum Notes
size 50 250 This is the number of elements per page.
offset 0 N/A This is the number of items to offset away from the first item in the list.


Filter/Search

The results of Index actions can be filtered/searched. The index URLs can take either one of the query strings: "?startswith==xxx" or "?contains==xxx," where "xxx" is the key word. If the request specifies more than one of these two query strings, a 400 HTTP error will be returned. Different fields will be searched depending on the resource type, see below.

Note that "0-9" is a reserved key word for query string "startswith." It represents any result starting with numbers.

Index Actions Where the key word will be searched
Customer Customer name, account number, reference number
Domain Domain name
Mailbox Mailbox name, mailbox display name
Contact Contact display name, external email
Group Group name, group display name
Mobile Service Associated mailbox name, mailbox display name


Reference Number

For the customer object only, the query string "referenceNumber=xxx" searches for a customer with an exact reference number. The result if found is the detail page of the customer.

Examples

Ruby

This examples is written in Ruby. To make the examples shorter, helper methods have been written. These methods are part of a NetMethods module. The contents of the NetMethods module is listed below.

module NetMethods 
  def get(url_string, format)
    url = URI.parse('http://' + server_host + server_port + version + url_string)
    @response = Net::HTTP::start(url.host, url.port)  do |http|
      sign_request
      assign_format(format)
      @request = Net::HTTP::Get.new(url.path, @headers)
      
      http.request(@request)
    end
  end
  
  def post(url_string, format, fields_hash)
    url = URI.parse('http://' + server_host + server_port + version + url_string)

    sign_request
    assign_format(format)
    @request = Net::HTTP::Post.new(url.path, @headers)
	
    @request.set_form_data(fields_hash)
    @response = Net::HTTP::start(url.host, url.port) do |http| 
      http.request(@request)
    end
  end

  def assign_format (format)
    @headers['Accept'] = format
  end
    
  def sign_request
    userAgent = 'Ruby Test Client'
    timestamp = DateTime.now.new_offset.strftime('%Y%m%d%H%M%S00')
    apiKey = 'XXXXXXXXXXXXXXXXXXXX'
    secretKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    
    data_to_sign = apiKey + userAgent + timestamp + secretKey
    
    signature = Base64.encode64(Digest::SHA1.digest(data_to_sign))
    
    @headers = Hash.new
    @headers['User-Agent'] = userAgent
    @headers['X-Api-Signature'] = apiKey + ":" + timestamp + ":" + signature 
  end
  
  def server_host
    'api.emailsrvr.com'
  end
  
  def server_port
    '80'
  end

  def version
    '/v0'
  end
end 


C#

This examples is written in C#.

using System;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Text;
using System.Net;

public class WebMethods
{
  private WebClientBase client;
  private string baseUrl;
  private string apiKey;
  private string secretKey;

  public WebMethods(WebClientBase client, string baseUrl, string apiKey, string secretKey)
  {
    this.client = client;
    this.baseUrl = baseUrl;
    this.apiKey = apiKey;
    this.secretKey = secretKey;
  }

  public virtual string Get(string url)
  {
    return MakeRemoteCall((client) =>
      {
        return client.DownloadString(baseUrl + url);
      },
      format);
  }

  public virtual string Post(string url, NameValueCollection data)
  {
    return MakeRemoteCall((client) =>
      {
        var bytes = client.UploadValues(baseUrl + url, data);
        return Encoding.UTF8.GetString(bytes);
      },
      format);
  }

  private void SignMessage()
  {
    var userAgent = "C# Client Library";
    client.Headers["User-Agent"] = userAgent;

    var dateTime = DateTime.UtcNow.ToString("yyyyMMddHHmmssff");

    var dataToSign = apiKey + userAgent + dateTime + secretKey;
    var hash = SHA1.Create();
    var signedBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(dataToSign));
    var signature = Convert.ToBase64String(signedBytes);

    client.Headers["X-Api-Signature"] = apiKey + ":" + dateTime + ":" + signature;
  }

  private void AssignFormat(string format)
  {
    client.Headers["Accept"] = format;
  }

  private string MakeRemoteCall(Func<WebClientBase, string> remoteCall, string format)
  {
    try
    {
      SignMessage();
      AssignFormat(format);
      return remoteCall.Invoke(client);
    }
    catch (WebException e)
    {
      throw new ApiException(e);
    }
  }
}

PHP

<?php
class WebMethods
{
    public function get($url, $format)
    {
        $headers = array();
        $this->signRequest($headers);
        $this->assignFormat($headers, $format);

        $session = curl_init($url);
        curl_setopt($session, CURLOPT_HEADER, true);
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($session);
        curl_close($session);
    }

    public function post($url, $fields, $format)
    {
        $headers = array();
        $this->signRequest($headers);
        $this->assignFormat($headers, $format);

        $session = curl_init($url);
        curl_setopt($session, CURLOPT_HEADER, true);
        curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($session, CURLOPT_POST, true);
        curl_setopt($session, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($session);
        curl_close($session);
    }


    public function signRequest(&$headers)
    {
        $user_agent = 'Api Test';
        $time_stamp = 'YYYYMMDDHHmmssff';
        $api_key = 'XXXXXXXXXXXXXXXXXXXX';
        $secret_key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

        $data_to_sign = $api_key . $user_agent . $time_stamp . $secret_key;
        $signature = base64_encode(sha1($data_to_sign, true));

        $headers[] = "User-Agent: $user_agent";
        $headers[] = "X-Api-Signature: $api_key:$time_stamp:$signature";
    }

    public function assignFormat(&$headers, $format)
    {
        $headers[] = "Accept: $format";
    }
}
?>