This documentation is for WSO2 Enterprise Service Bus version 4.7.0 . View documentation for the latest release.
Skip to end of metadata
Go to start of metadata

This page provides fundamental information that help you get started using REST APIs with WSO2 ESB. It contains the following sections:

Introduction to configuring the APIs

Representational State Transfer (REST) provides a lightweight approach for building distributed systems. Instead of relying on overly complicated protocol stacks and heavyweight middleware, REST facilitates communication between systems by leveraging simple message formats and open protocols that power the Web. This section introduces the fundamentals of working with REST APIs. It illustrates the concepts through the XML configuration. For information on adding an API through the Management Console UI, see Adding APIs in the Management Console

Defining an API

The syntax of a REST API is as follows.

<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"]>

An API definition is identified by the <api> tag. Each API must specify a unique name and a unique URL context (see below). A REST 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. For example:

<api name="API_1" context="/order">
    <resource url-mapping="/list" inSequence="seq1" outSequence="seq2"/>

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.

Specifying the context

A REST API in WSO2 ESB is analogous to a web application deployed in the ESB runtime. 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.

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 , the following requests will be handled by your API:

Using patterns with resources

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.

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)

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)


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:


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


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}”:


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

The ESB 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, 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 WSO2 ESB. For example:

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

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

LogMediator Character = c, Word = cat


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 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 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">
                  <endpoint key="BackendService"/>
    <resource inSequence="seq10" outSequence="seq11"/>

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 REST APIs with the ESB, see the article How to GET a Cup of Coffee the WSO2 Way.

Adding APIs in the Management Console

You can easily add APIs using the Management Console.

To add an API:

  1. In the Management Console, click the Main tab.

  2. Under Manage -> Service Bus, click APIs.
    The Deployed APIs dialog appears, displaying the APIs you've already created. Before you create a new API, you should browse the list to see whether an API already exists that will suit your needs. You can easily find an existing API by entering all or part of its name in the Search field and then clicking the Search icon.
  3. Click Add API.

    The Add API dialog appears.

  4. Specify the following:
    • A unique name for this API.
    • The context, and optionally the hostname and port (see Specifying the context for more information).
  5. Click Add Resource, and then scroll down to see the additional fields.
  6. Specify the HTTP method to use for this invocation (see Best practices for designing REST APIs for more information).
  7. In the URL Style list, select whether you're specifying a URL mapping or URI template, and then specify the pattern in the box that appears (see Using patterns with resources for more information). 
  8. Specify the In, Out, and Fault sequences as needed by taking one of the following approaches for each:
    • To omit the sequence, leave it set to None.
    • To create a new sequence, click Define Inline, click Create, and then define the sequence as described in Adding a Mediation Sequence.
    • To use an existing sequence in the registry, click Pick From Registry, and then select the sequence from the local, Configuration, or Governance registry (see Working with the Registry).
    • To use an existing sequence in the Synapse configuration, click Use Existing Sequence and select it from the drop-down list.
  9. Click Update to apply the resource to the configuration.
  10. Click Add Resource again and repeat these steps to add additional resources as needed. When you have finished defining the API, click Save.

The API now appears in the list of deployed APIs.

Basic REST architectural principles

This section highlights some of the basic architectural principles of REST based on the following resources:

Uniform interface

REST provides a uniform interface between clients and servers, which simplifies and decouples the architecture, allowing both to evolve independently. To achieve a uniform interface, the following constraints are applied:

  • Resource-based: Individual resources are identified in requests using URIs as resource identifiers.

  • Manipulation of resources through representations: When a client holds a representation of a resource, including any metadata attached, it has enough information to modify or delete the resource on the server, provided it has the permission to do so.

  • Self-descriptive messages: Each message includes enough information to describe how to process the message.

  • Hypermedia as the engine of application state (HATEOAS): Clients deliver state via body contents, query-string parameters, request headers, and the requested URI. Services deliver state to clients via body content, response codes, and response headers. This is technically referred to as hypermedia (or hyperlinks within hypertext).


The necessary state to handle the request is contained within the request itself, whether as part of the URI, query-string parameters, body, or headers.


As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable or non-cacheable to prevent clients from reusing stale or inappropriate data in response to further requests.


The uniform interface separates clients from servers. For example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface is not altered.

Layered system

A client cannot ordinarily detect whether it is connected directly to the back-end server or to an intermediary along the way. This allows for load balancing and caching.

Best practices for designing REST APIs

This section highlights some best practices from to keep in mind when designing your APIs.

  • Use meaningful resource names to clarify what a given request does. A RESTful URI should refer to a resource that is a thing instead of an action. The name and structure of URIs should convey meaning to those consumers.
  • Use plurals in node names to keep your API URIs consistent across all HTTP methods.
  • Use HTTP methods appropriately. Use POST, GET, PUT, and DELETE in requests to clarify the purpose of the request. These methods map to the CRUD methods Create, Read, Update, and Delete, respectively.
  • Offer both XML and JSON whenever possible.
  • Use abstraction when it's helpful. The API implementation does not need to mimic the underlying implementation. 
  • Implement resource discoverability through links (HATEOAS). As mentioned in the previous section, the application state should be communicated via hypertext. The API should be usable and understandable given an initial URI without prior knowledge or out-of-band information.
  • Version your APIs as early as possible in the development cycle.
  • Secure your services using OAuth2, OpenID, or another authentication/authorization mechanism. See also Securing REST APIs .


  • No labels