2. Defining an API

First of all, you need to decide what functionality you want to expose via an API.

Once you have a clear idea of what you want, you need to write an API definition class describing the set of methods in the API, and their signatures.

The API definition class must derive from ActionWebService::API::Base. It can’t be instantiated.

Declare each method in the API using #api_method, optionally specifying the method parameter and return value signature.

Example API definition class

  
    class PersonAPI < ActionWebService::API::Base
      api_method :new_person, :expects => [:string, :string], :returns => [:int]
    end
  

This example declares PersonAPI to be an API with one method: new_person.

This method expects two parameters, both strings, and returns an integer.

Conceptually, this is what the method would look like:

  
    def new_person(firstname, lastname)
      1
    end
  

The actual implementation may differ, depending on the dispatching mode (see chapter 3).

The :expects and :returns options to #api_method are optional, but if present, will require that anyone trying to call this method must satisfy the method parameter requirements.

:expects and :returns are signature options, meaning their values are expected to be in signature definition format.

Signatures add information to an API method to help Ruby to interoperate with static languages, and to add missing information such as parameter names.

Signature options to #api_method

Option Explanation
:expects Indicates how many method arguments exist, and also the type of those arguments.
:returns Indicates the type of the method return value.


If you omit :expects, Action Web Service will raise an error if callers try to supply arguments.

If you omit :returns, Action Web Service will discard the method return value, and will not return anything at all.

Format of signatures

A signature is always an array that contains one or more parameter specifiers.

Parameter Specifiers

A parameter specifier describes the type and optionally, the name of a single signature parameter.

The parameter specifier can be one of:

  1. A symbol or a string identifying one of the Action Web Service base types. The list of Action Web Service base types can be found in the API documentation for ActionWebService::Signature.
  1. The Class object of a custom structured type (such as an ActionWebService::Struct or ActiveRecord::Base)
  1. A single-element array containing #1 or #2 as element
  1. A Hash containing as key the name of parameter and as value #1, #2 or #3

Example signatures

Signature Explanation
[[:string]] An string array parameter
[:bool] A boolean parameter
[Person] A Person structured type parameter
[{:lastname=>:string}] A string parameter, with a name of lastname in generated WSDL
[:int, :int] Two integer parameters