This site contains the documentation that is relevant to older WSO2 product versions and offerings.
For the latest WSO2 documentation, visit https://wso2.com/documentation/.

Working with APIs

A REST API is only one way of triggering a mediation flow defined in the ESB of WSO2 Enterprise Integrator (WSO2 EI). Alternatively, you can use Proxy ServicesInbound Endpoints, or Scheduled Tasks.  REST APIs allow you to send messages directly to the ESB profile,  which will then execute a specific logic based on the instructions in the HTTP call.

To get started with REST APIs in the ESB, follow the tutorial on sending a simple message to a service.

The following topics provide additional information on how to configure an API in the ESB profile.

 

Overview of REST APIs

Each API must specify a unique name and a unique URL Context. An API is made of one or more Resources, which is a logical component of an API that can be accessed by making a particular type of HTTP call.  Once a request is dispatched to a resource it will be mediated through the in-sequence of the resource. At the end of the in-sequence, the request can be forwarded to a back-end application for further processing. Any responses coming from the back-end system are mediated through the out-sequence of the resource. You can also define a fault-sequence to handle any errors that may occur while mediating a message through a resource.

The syntax of a REST API is given below. An API definition is identified by the <api> tag, and the resource definition is identified by the <resource> tag.

<api name="API_NAME" context="URI_PATH_OF_API" [hostname="HOST_NAME_OF_SERVER"]  [port="PORT_NUMBER"]>
	<resource [methods="GET|POST|PUT|DELETE|OPTIONS|HEAD|PATCH"] [uri-template="URI_TEMPLATE"|url-mapping="URL_MAPPING"]>
	  <inSequence>
        ...
      </inSequence>?
      <outSequence>
         ...
      </outSequence>?
	  <faultSequence>
         ...
      </faultSequence>?
	</resource>
</api>

The URL context

An API in WSO2 EI is analogous to a web application deployed in the ESB profile. Each API is anchored at a user-defined URL context, much like how a web application deployed in a servlet container is anchored at a fixed URL context. An API will only process requests that fall under its URL context. For example, if a particular API is anchored at the context “/test”, only HTTP requests whose URL path starts with “/test” will be handled by that API.

If your EI is deployed in multi-tenancy mode, you must add the tenant domain to the API context when defining the API in the Source view instead of the Design view in the Management Console. For example, if you are defining the API in the tenant abc.com, and the context for the API is /order, you would specify the context as: context="/t/abc.com/order". If you define the API in the Design view, however, the tenant domain is automatically prepended to the context, so you would just specify the context as /order without the tenant.

It is also possible to bind a given API to a user-defined hostname and/or a port number. For example, if your API is anchored at the URL http://your.host.name/test , the following requests will be handled by your API:

http://your.host.name/test/getNumbers
http://your.host.name/test/calculation/getRate

Version your APIs as early as possible in the development cycle. At present, the EI identifies each API by its unique context name. If you introduce a version in the API context (e.g., /Service 1.0.0), you can update it when you upgrade the same API (e.g., /Service 1.0.1)

The API Host and Port

When you define the API, you can also specify the Host at which the API is anchored as well as the Port of the REST API.

The API Resource

A resource can be associated with a user-defined URL mapping or URI template , which allow us to restrict the type of HTTP requests processed by a particular resource. A resource can also be bound to a specific subset of HTTP verbs and header values, providing additional control over what requests are handled by a given resource. The resource also contains sequences (in-sequence/out-sequence/fault sequence), which contains the mediation logic to process the message.

Sequences

In-sequence/Out-sequence/Fault sequence.

  • None: Select this to omit the sequence.
  • Define Inline: Select this if you want to define a new sequence and then define the sequence as described in Adding a Mediation Sequence.
  • Pick From Registry: Select this to use an existing sequence saved in the Registry.
  • Use Existing Sequence: Select this to use an existing sequence that already exists in the Synapse Configuration.

URL mappings

When a resource is defined with a URL mapping, only those requests that match the given pattern will be processed by the resource. There are three types of URL mappings:

  • Path mappings (/test/*, /foo/bar/*)

  • Extension mappings (*.jsp, *.do)

  • Exact mappings (/test, /test/foo)

For example, consider a resource associated with the URL mapping “/foo/*” and the HTTP verb “GET”. This approach ensures that the resource will only process GET requests whose URL path matches the pattern “/foo/*”. Therefore, the following requests would be processed and mediated by the resource:

GET /test/foo/bar 
GET /test/foo/a?arg1=hello 

The following HTTP requests would not be handled by this resource:

GET /test/food/bar (URL pattern does not match)
POST /test/foo/bar (HTTP verb does not match)

URI templates

A URI template represents a class of URIs using patterns and variables. When a resource is associated with a URI template, all requests that match the template will be processed by the resource. Some examples of valid URI templates are as follows:

/order/{orderId}
/dictionary/{char}/{word}

The identifiers within curly braces are considered variables. For example, a URL that matches the template “/order/{orderId}” is as follows:

/order/A0001

In the above URL instance, the variable "orderId" has been assigned the value “A0001”. Similarly, the following URL adheres to the template “/dictionary/{char}/{word}”:

/dictionary/c/cat

In this case, the variable “char” has the value “c” and the variable “word” is given the value “cat”.

The ESB profile provides access to the exact values of the template variables through message context properties. For example, if you have a resource configured with the URI template “/dictionary/{char}/{word}”, and a request “/dictionary/c/cat” is sent to the ESB profile, it will be dispatched to this resource, and we will be able to retrieve the exact values of the two variables using the "get-property" XPath extension of the ESB profile  and prefixing the variable with "uri.var." as shown in the following example:

<log level="custom">
   <property name="Character" expression="get-property('uri.var.char')"/>
   <property name="Word" expression="get-property('uri.var.word')"/>
</log>

This log mediator configuration would generate the following output for the request “/dictionary/c/cat”:

LogMediator Character = c, Word = cat

Example APIs

Let's look at some sample API configurations to understand how we use context, resources, and patterns to control how requests are processed.

<api name="API_1" context="/order">
    <resource url-mapping="/list" inSequence="seq1" outSequence="seq2"/>
</api>
 
<api name="API_2" context="/user">
    <resource url-mapping="/list" methods="GET" inSequence="seq3" outSequence="seq4"/>
    <resource uri-template="/edit/{userId}" methods="PUT POST" inSequence="seq5" outSequence="seq6"/>
</api>

<api name="API_3" context="/payments">
    <resource url-mapping="/list" methods="GET" inSequence="seq7" outSequence="seq8"/>
    <resource uri-template="/edit/{userId}" methods="PUT POST" outSequence="seq9">
        <inSequence>
             <log/>
             <send>
                  <endpoint key="BackendService"/>
             </send>
        </inSequence>
    </resource>
    <resource inSequence="seq10" outSequence="seq11"/>
</api>

You can define a URL mapping to a set of operations as shown in the API_1 definition, or you can define separate mappings for separate operations as shown in API_2. Also note the last resource definition in API_3, which does not specify a URL mapping nor a URI template. This is called the default resource of the API. Each API can have at most one default resource. Any request received by the API that does not match any of the enclosed resource definitions will be dispatched to the default resource of the API. In the case of API_3, a DELETE request on the URL “/payments” will be dispatched to the default resource as none of the other resources in API_3 are configured to handle DELETE requests.

For a comprehensive example of using APIs with the ESB profile, see the article How to GET a Cup of Coffee the WSO2 Way.

Configuring non-HTTP endpoints

When using a non-HTTP endpoint, such as a JMS endpoint, in the API definition, you must remove the REST_URL_POSTFIX property to avoid any characters specified after the context (such as a trailing slash) in the request from being appended to the JMS endpoint. For example:

<api xmlns="http://ws.apache.org/ns/synapse" name="EventDelayOrderAPI" context="/orderdelayAPI"> 
    <resource methods="POST" url-mapping="/"> 
       <inSequence> 
          <property name="REST_URL_POSTFIX" action="remove" scope="axis2"></property> 
          <send> 
             <endpoint> 
                <address uri=
"jms:/DelayOrderTopic?transport.jms.ConnectionFactoryJNDIName=TopicConnectionFactory&
java.naming.factory.initial=org.apache.activemq.jndi.ActiveMQInitialContextFactory&
java.naming.provider.url=tcp://localhost:61616&transport.jms.DestinationType=topic">
              </address> 
             </endpoint> 
          </send> 
       </inSequence> 
    </resource> 
 </api>

Notice that we have specified the REST_URL_POSTFIX property with the value set to "remove". When invoking this API, even if the request contains a trailing slash after the context (e.g., POST http://127.0.0.1:8287/orderdelayAPI / instead of POST http://127.0.0.1:8287/orderdelayAPI ), the endpoint will be called correctly.

Generating Swagger documents for the APIs

API documentation is important to guide the users on what they can do using specific APIs. Follow the steps given below to generate Swagger documentation for the REST APIs you created in WSO2 EI.

You need to have created a REST API to view the documentation for that API.

  1. Add the following configuration under the HttpGetRequestProcessors tag of the <EI_HOME>/conf/carbon.xml file to generate the Swagger JSON or YAML files.

    <Processor>
       <Item>swagger.json</Item>
       <Class>org.wso2.carbon.mediation.transport.handlers.requestprocessors.swagger.format.SwaggerJsonProcessor</Class>
    </Processor>
    <Processor>
       <Item>swagger.yaml</Item>
       <Class>org.wso2.carbon.mediation.transport.handlers.requestprocessors.swagger.format.SwaggerYamlProcessor</Class>
    </Processor>
  2. Open the terminal, navigate to the <EI_HOME>/bin directory and start the WSO2 EI profile.

    Linux/Mac./integrator.sh
    Windowsintegrator.bat --run
  3. Generate the Swagger docs:

    JSON
    Enter the following on the browser and the JSON content will appear on the browser screen: http://<EI_HOST>:8280/<API_NAME>?swagger.json
    • By default, <EI_HOST> is localhost. However, if you are using a public IP, the respective IP address or domain needs to be specified.
    • Enter the APIs name for <API_NAME>.

      The API name is case sensitive. Therefore, make sure to the enter the API name correctly. Else, the JSON file will not download.

    Example: http://localhost:8280/HealthcareAPI?swagger.json

    Generate Swagger docs for tenants

    If you want to generate the Swagger JSON file for a tenant, you need to enter the following on the browser. http://<EI_HOST>:8280/t/<TENANT_DOMAIN>/<API_NAME>?swagger.json
    • By default, <EI_HOST> is localhost. However, if you are using a public IP, the respective IP address or domain needs to be specified.
    • Enter the value of the tenant domain for <TENANT_DOMAIN>.
    • Enter the APIs name for <API_NAME>.

    Example: http://localhost:8280/t/abc.com/HealthcareAPI?swagger.json

    YAML
    Enter the following on the browser and the YAML file will download to your machine: http://<EI_HOST>:8280/<API_NAME>?swagger.yaml
    • By default, <EI_HOST> is localhost. However, if you are using a public IP, the respective IP address or domain needs to be specified.
    • Enter the APIs name for <API_NAME>.

      The API name is case sensitive. Therefore, make sure to the enter the API name correctly. Else, the YAML file will not download.

    Example: http://localhost:8280/HealthcareAPI?swagger.yaml

    Generate Swagger docs for tenants
    If you want to generate the Swagger YAML file for a tenant, you need to enter the following on the browser.

    http://<EI_HOST>:8280/t/<TENANT_DOMAIN>/<API_NAME>?swagger.yaml
    • By default, <EI_HOST> is localhost. However, if you are using a public IP, the respective IP address or domain needs to be specified.
    • Enter the value of the tenant domain for <TENANT_DOMAIN>.
    • Enter the APIs name for <API_NAME>.

    Example: http://localhost:8280/t/abc.com/HealthcareAPI?swagger.yaml

  4. Copy the content of the JSON or YAML file to the Swagger Editor or any other tool and check out the documentation of the API.