Sunteți pe pagina 1din 267

WSO2 API Cloud

WSO2 API Cloud


Documentation
WSO2 API Cloud

Table of Contents
1. WSO2 API Cloud Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Key Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.3.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.1.1 Create and Publish an API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
1.3.1.2 Subscribe to and Invoke an API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.3.1.3 Invoke an API using cURL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.3.2 API Publishing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.3.2.1 Add API Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
1.3.2.2 Change the Default Mediation Flow of API Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
1.3.2.3 Convert a JSON Message to SOAP and SOAP to JSON . . . . . . . . . . . . . . . . . . . . . . . . . 57
1.3.2.4 Create APIs using a Swagger URL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
1.3.2.5 Create a Prototyped API with an Inline Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
1.3.2.6 Manage the API Lifecycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
1.3.2.6.1 Create a new API Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
1.3.2.6.2 Deploy and Test as a Prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
1.3.2.6.3 Publish the new Version and Deprecate the old . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
1.3.2.7 Migrate your APIs between Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
1.3.2.7.1 Migrating your API from the APIM Local Setup to WSO2 API Cloud . . . . . . . . . . . . 90
1.3.2.7.2 Migrating your API from WSO2 API Cloud to a APIM Local Setup . . . . . . . . . . . . . 95
1.3.2.8 Publish and Invoke a SOAP API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
1.3.3 Backend Integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
1.3.3.1 Pass a Custom Authorization Token to the Backend . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
1.3.3.2 Connect to your Backend Services from WSO2 API Cloud . . . . . . . . . . . . . . . . . . . . . . . . 120
1.3.3.2.1 Expose your On-Premises Backend Services to the API Cloud . . . . . . . . . . . . . . . . 120
1.3.3.2.2 Secure your Backend Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
1.3.4 Developer Portal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
1.3.4.1 Use the Community Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
1.3.4.2 Customize the API Store Theme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
1.3.4.3 Customize Cloud URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
1.3.5 Policies and Monetization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
1.3.5.1 Enforce Throttling and Resource Access Policies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
1.3.5.2 Enable Monetization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
1.3.6 User Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
1.3.6.1 Register and Invite Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
1.3.6.2 Block Subscription to an API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
1.3.6.3 Enable Self Signup to the API Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
1.3.6.4 Authenticate Users that are External to WSO2 Cloud . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
1.3.6.5 Customize Invitation Emails . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
1.4 Analytics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
1.4.1 Viewing API Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
1.4.2 Managing Alerts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
1.4.2.1 Alert Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
1.4.2.2 Subscribing for Alerts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
1.4.3 Analyzing Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
1.4.3.1 Viewing Live Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

Copyright © WSO2 Inc. 2014-2017 2


WSO2 API Cloud

1.4.3.2 Analyzing the Log Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221


1.4.3.3 Analyzing Application Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
1.4.3.4 Analyzing API Deployment Statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
1.4.3.5 Analyzing Login Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
1.4.3.6 Analyzing the Number of API Failures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
1.5 Cloud Administration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
1.6 WSO2 APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
1.6.1 Common Cloud APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
1.6.2 Publisher APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
1.6.3 Store APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
1.6.4 Token API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
1.6.4.1 Authorization Code Grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
1.6.4.2 Refresh Token Grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
1.6.4.3 Password Grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
1.6.4.4 SAML Extension Grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
1.6.4.5 Client Credentials Grant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
1.7 FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

Copyright © WSO2 Inc. 2014-2017 3


WSO2 API Cloud

WSO2 API Cloud Documentation


WSO2 API Cloud delivers enterprise-ready solution for creating, publishing and managing all aspects of an API
and its lifecycle.

To register and get started, go to http://wso2.com/cloud/api-cloud/.

Get started with WSO2 API Cloud

What is
WSO2
API
Cloud
How can
WSO2
API Cloud
help your
business.

Copyright © WSO2 Inc. 2014-2017 4


WSO2 API Cloud

Key
Concepts

Learn
about
WSO2
API
Cloud.

Tutorials
Try out
the user
stories.

To download a PDF of this document or a selected part of it, click here (only generates one PDF at a time). You
can also use this link to export to HTML or XML.

Copyright © WSO2 Inc. 2014-2017 5


WSO2 API Cloud

Introduction
WSO2 API Cloud is an enterprise-ready, self-service platform that enables you to expose business capabilities as
managed APIs and leverage off-the-shelf potential for advertising and selling business APIs. The API Cloud
supports all aspects of an API's lifecycle, from its creation to publication and retirement.

The API Cloud is based on WSO2 API Manager, WSO2's complete solution for designing and publishing APIs and
managing a developer community.

Advantages of the API Cloud


Provides a pre-setup environment that is ready to go and saves time on infrastructure set up.
Reduces the cost of development and time-to-market because developers understand what capabilities are
already available as APIs and ready for reuse before starting a new development project.
Helps build a digital business ecosystem. The API Cloud fosters cross-organizational development
collaboration by making your APIs public in a storefront and encouraging reuse.
Enables platform service sharing by tenant-aware and service-aware load balancing.
Frees enterprises from vendor locking. You can start hosting and managing your APIs on the API Cloud
and then migrate between an on-premises instance, a private PaaS, a public PaaS, and hybrid cloud
environments without rewriting code or reentering data.
Helps manage and monitor APIs through various statistical dashboards.
Provides a consistent, easy-to-use, check-box GUI for creating and managing API and a developer
community.
The platform automatically manages dependencies for you. For example, when moving an API from the
CREATED state to PUBLISHED state, you usually have to connect to different databases. But now, the
publisher can simply move the application through its lifecycle stages while the platform automatically
handles the underlying tasks.

Copyright © WSO2 Inc. 2014-2017 6


WSO2 API Cloud

Key Concepts
Let's take a look at some concepts and terminology that you need to know in order to follow the use cases.

[ APICloud's user model ] [ API Cloud's components ] [ Users and roles ] [ API Lifecycle ] [ Applications ] [ Access
tokens ] [ User access tokens ] [ Application access tokens ] [ Throttling ] [ API visibility and subscription ] [ API
resources ] [ Swagger API Console ] [ OAuth scopes ] [ Endpoints ] [ Sequences ] [ Mediators ] [ Response caching ] [ G
ateway caching ]

API Cloud's user model

You can register to all of the WSO2 public cloud offerings (e.g., the Integration Cloud, the API Cloud) using a valid
email address, and create multiple organizations under the same login. The system creates a unique tenant domain
name for each organization you create. The user who creates an organization is assigned admin rights to it.

Click to read more...


In the public cloud, users are authorized by their email addresses and are decoupled from organizations and tenant
domains. This allows one user to be in multiple organizations (tenant domains) at the same time and log in to each
organization using a single email address. If users are added to more than one organization, they are prompted to
select the organization before loggingin toits cloud.

Diagram: WSO2 Cloud's user model

API Cloud's components

The API Cloud comprises of the API Publisher, Store, Gateway and the Key Manager. Given below is a description
of each components:

Click to read more...

API Gateway: Secures, protects, manages, and scales API calls. It is a simple API proxy that intercepts API
requests and applies policies such as throttling and security. It also gathers API usage statistics.
API Key Manager: Handles all security and key-related operations. API gateway connects with the key

Copyright © WSO2 Inc. 2014-2017 7


WSO2 API Cloud

manager to check the validity of OAuth tokens when APIs are invoked. The key manager also provides a
token API to generate OAuth tokens that can be accessed via the Gateway.

When the API Gateway receives API calls, it contacts the Key Manager service to verify the validity of the
tokens and do security checks. For example, when the Gateway receives a log call, it forwards the calls to the
Key Manager server. You must pass username, password, consumer key and consumer secret key with it to
register. All tokens used for validation are based on OAuth 2.0.0 protocol. Secure authorization of APIs is
provided by the OAuth 2.0 standard for key management. The API Gateway supports API authentication with
OAuth 2.0, and enables IT organizations to enforce rate limits and throttling policies.

When the API Gateway receives API invocation calls, it similarly contacts the API Key Manager service for
verification. This verification call happens every time the Gateway receives an API invocation call if caching i
s not enabled at the Gateway level. For this verification, the Gateway passes an access token, the API and
its version to the Key Manager.

Communication between API Gateway and Key Manager happens either through a Web service call or a
Thrift call. The default communication protocol is Thrift, which is an RPC framework used to develop scalable,
cross-language services. Thrift is much faster than SOAP over HTTP communication.

API Publisher: Enables API providers to publish APIs, share documentation, provision API keys and gather
feedback on API features, quality and usage. The API Publisher is opened automatically when you sign in to
the API Cloud.
API Store: Enables API consumers to discover API functionality, subscribe to APIs, evaluate them and
interact with API publishers. Any user can view the stores of all tenants registered in the Cloud. If you know
the name of the tenant, you can access its store using the URL http://<hostname>/Store?tenant=<t
enant_name> .
Additionally, statistics are provided by the monitoring component, which integrates with WSO2 BAM.

Users and roles

The API Cloud offers distinct community roles that are applicable to most enterprises:

APICloudPublisher: a publisher manages a set of APIs across the enterprise or business unit and controls
the API lifecycle, subscriptions, and monetization aspects. The publisher is also interested in usage patterns
for APIs and has access to all API statistics.
APICloudSubscriber: a subscriber uses the API store to discover APIs, read the documentation, and
forums, rate/comment on the APIs, subscribes to APIs, obtain access tokens, and invoke the APIs.

API Lifecycle

An API is the published interface, while the service is the implementation running in the backend. APIs have their
own lifecycles that are independent to the backend services they rely on. This lifecycle is exposed in the API
publisher Web interface and is managed by the API publisher role.

The following stages are available in the default API lifecycle:

Click to read more...

CREATED: API metadata is added to the API Store, but it is not deployed in the API gateway and therefore,
is not visible to subscribers in the API Store.
PROTOTYPED: the API is deployed and published in the API Store as a prototype.Aprototyped API is usually
a mock implementation made public in order to get feedback about its usability. Users can invoke the API
without a subscription.
PUBLISHED: The API is visible in the API Store and available for subscription.
DEPRECATED: When an API is deprecated, new subscriptions are disabled. But the API is still deployed in
the Gateway and is available at runtime to existing subscribers. Existing subscribers can continue to use it as
usual until the API is retired.

Copyright © WSO2 Inc. 2014-2017 8


WSO2 API Cloud

RETIRED: The API is unpublished from the API gateway and deleted from the store.
BLOCKED: Access to the API is temporarily blocked. Runtime calls are blocked and the API is not shown in
the API Store anymore.

Applications

An application is a logical collection of APIs. An application is primarily used to decouple the consumer from the
APIs. It allows you to :

Generate and use a single key for multiple APIs


Subscribe multiple times to a single API with different SLA levels

You subscribe to APIs through an application. Applications are available at different SLA levels and have
application-level throttling tiers engaged in them. A throttling tier determines the maximum number of calls you can
make to an API during a given period of time.

The API Cloud comes with a pre-created, default application. You can also create your own applications.

Access tokens

An access token is a simple string that is passed as an HTTP header of a request. For example, " Authorizatio
n: Bearer NtBQkXoKElu0H1a1fQ0DWfo6IX4a ." Access tokens authenticate API users and applications, and
ensure better security (e.g., prevent DoS attacks ). If a token that is passed with a request is invalid, the request is
discarded in the first stage of processing. Access tokens work equally well for SOAP and REST calls.

There are two types of access tokens:

Click to read more...

User access tokens


Application access tokens

User access tokens

Tokens to authenticate the final user of an API. User access tokens allow you to invoke an API even from a
third-party application like a mobile app. You generate/renew a user access token by calling the Login API through
a REST client. For more information, see Token API.

Application access tokens

Tokens to authenticate an application, which is a logical collection of APIs. You to access all APIs associated with
an application using a single token, and also subscribe multiple times to a single API with different SLA levels.
Application access tokens leverage OAuth2 to provide simple key management.

The steps below describe how to generate/renew application access tokens:

1. Log in to the API Store.


2. Click the Applications menu and then click the application to open it. For example,

Copyright © WSO2 Inc. 2014-2017 9


WSO2 API Cloud

3. Under the Production Keys tab, scroll down and click Regenerate .

Throttling

Throttling allows you to limit the number of successful hits to an API during a given period of time, typically in cases
such as the following:

Copyright © WSO2 Inc. 2014-2017 10


WSO2 API Cloud

To protect your APIs from common types of security attacks such as denial of service (DOS).
To regulate traffic according to infrastructure availability.
To make an API, application or a resource available to a consumer at different levels of service, usually for
monetization purpose.

See Working with Throttling in the WSO2 API Manager documentation for detailed information about throttling,
throttling limits, policies etc.

API visibility and subscription

Visibility settings prevent certain user roles from viewing and modifying APIs created by another user role.

Public: the API is visible to all users (registered and anonymous), and can be advertised in multiple stores
(central and non-WSO2 stores).
Visible to my domain: the API is visible to all users who are registered to the API's tenant domain.
Restricted by Roles: The API is visible to its tenant domain and only to the user roles that you specify. Acce
pted roles are admin, publisher, subscriber and appclouduser.

Given below is how visibility levels work for users in different roles:

Click to read more...

API creator and publisher roles can see all APIs in their tenant store even if you restrict access to them.
This is because those roles have permission to view and edit all APIs in the API Publisher, and therefore,
does not have to be restricted in the Store.
Anonymous users can only see APIs that have visibility as Public .
Registered users can see
public APIs of all tenant domains
all APIs in the registered user's tenant domain as long as the API is not restricted to a role that the
user is assigned to

An API's visibility is directly related to the API's subscription availability because you cannot subscribe to
something you don't see in the store. The diagram below depicts this relationship:

Copyright © WSO2 Inc. 2014-2017 11


WSO2 API Cloud

API resources

An API is made up of one or more resources. Each resource handles a particular type of request and is analogous
to a method (function) in a larger API.

API resources accept following attributes:

Click to read more...

Attribute Description
name

OAuth OAuth scopes


Scopes

Copyright © WSO2 Inc. 2014-2017 12


WSO2 API Cloud

URL A URL pattern can be one of the following types:


Pattern
As a url-mapping. E.g., /state/town/*
As a uri-template. E.g., /{state}/{town}

The terms url-mapping and uri-template come from synapse configuration language. When an API is
published in the API Publisher, a corresponding XML definition is created in the API Gateway. This
XML file has a dedicated section for defining resources. See examples below:

<resource methods="POST GET" url-mapping="/state/town/*">


<resource methods="POST GET" uri-template="/{texas}/{houston}">

url-mapping performs a one-to-one mapping with the request URL, whereas the uri-template perf
orms a pattern matching.

Parametrizing the URL allows the API Manager to map the incoming requests to the defined resource
templates based on the message content and request URI. Once a uri-template is matched, the
parameters in the template are populated appropriately. As per the above example, a request made
to http://gatewa_host:gateway_port/api/v1/texas/houston sets the value of state to texas and the
value of town to houston. You can use these parameters within the synapse configuration for
various purposes and gain access to these property values through the uri.var.province and ur
i.var.district properties. For more information on how to use these properties, see Introduction
to REST API and the HTTP Endpoint of the WSO2 ESB documentation.

Also, see http://tools.ietf.org/html/rfc6570 on URI templates.

HTTP The HTTP methods that specify the desired action to be performed on the resource. These methods
Verb can be GET, POST, PUT, DELETE or OPTIONS. Multiple methods can be selected.

Auth The authentication type of each HTTP method of the resource. You can give one of the following:
Type
None: No authentication is applied and the API Gateway skips the authentication process
Application: Authentication is done by the application. The resource accepts application access
tokens.
Application User: Authentication is done by the application user. The resource accepts user
access tokens.
Application and Application User: Both application and application user level authentication is
applied. Note that if you select this option in the UI, it appears as Any in the API Manager's internal
data storage and data representation, and Any will appear in the response messages as well.

Note that for the resources that have HTTP verbs (GET, POST etc.) requiring authentication (i.e.,
Auth Type is not NONE), set None as the Auth type of OPTIONS. This is to support CORS (Cross
Origin Resource Sharing) between the API Store and Gateway. (The above screenshot shows this).

The auth type is cached in the API Manager for better performance. If you change the auth type
through the UI, it takes about 15 minutes to refresh the cache. During that time, the server returns the
old auth type from the cache. If you want the changes to be reflected immediately, please restart the
server after changing the auth type.

Once a request is accepted by a resource, it will be mediated through an in-sequence. Any response from the
backend is handled through the out-sequence. Fault sequences are used to mediate errors that might occur in either
sequence. Thedefaultin-sequence,out-sequenceandfault sequences are generated when the API is published.

Swagger API Console

Copyright © WSO2 Inc. 2014-2017 13


WSO2 API Cloud

WSO2 API Store provides an integrated Swagger U I, which is part of the Swagger project. You can use it for
interactive API documentation and to invoke APIs.

Swagger is a 100% open source, standard, language-agnostic specification and a complete framework for
describing, producing, consuming, and visualizing RESTful APIs, without the need of a proxy or third-party
services. Swagger allows consumers to understand the capabilities of a remote service without accessing its source
code and interact with the service with a minimal amount of implementation logic. Swagger helps
describe services in the same way that interfaces describe lower-level programming code.

The Swagger UI is a dependency-free collection of HTML, JavaScript, and CSS that dynamically generate
documentation from a Swagger-compliant API. Swagger-compliant APIs give you interactive documentation, client
SDK generation, and more discoverability. The Swagger UI has JSON code and its UI facilitates easier code
indentation, keyword highlighting and shows syntax errors on the fly. You can add resource parameters, summaries
and descriptions to your APIs using the Swagger UI.

The API Publisher has integrated Swagger to facilitate simple, interactive API documentation and invocation. The
documentation is given in a Swagger API definition, which is the JSON representation of the API that is created
using the information provided at the time the API is created. The Swagger JSON files are saved in the registry. Yo
u can edit the API definition using the Edit Swagger Definition button in the API Publisher.

Also, see the Swagger 2.0 specification.

OAuth scopes

Scopes enable fine-grained access control to API resources based on user roles. You define scopes to an API's
resource. When a user invokes the API, his/her OAuth 2 bearer token cannot grant access to any API resource
beyond its associated scopes.

You can apply scopes to an API resource at the time the API is created or modified. In the API Publisher, click the A
PI -> Add menu (to add a new API) or the Edit link next to an existing API. Then, navigate to the Manage tab and
scroll down to see the Add Scopes button. A screen such as the following appears:

Click to read more...

Scope Key A unique key for identifying the scope. Typically, it is


prefixed by part of the API's name for uniqueness,but is
not necessarily reader-friendly.

Scope Name A human-readable name for the scope. It typically says


what the scope does.

Copyright © WSO2 Inc. 2014-2017 14


WSO2 API Cloud

Roles The user role(s) that are allowed to obtain a token


against this scope. E.g., manager, employee.

To illustrate the functionality of scopes, assume you have the following scopes attached to resources of an API:

Assume that users named Tom and John are assigned the employee role and both the employee and manager
roles respectively.

Tom requests a token through the Token API as grant_type=password&username=nuwan&password=xxxx&


scope=news_read news_write. However, as Tom is not in the manager role, he will only be granted a token
bearing the news_read scope. The response from the Token API will be similar to the following:

"scope":"news_read","token_type":"bearer","expires_in":3299,
"refresh_token":"8579facb65d1d3eba74a395a2e78dd6",
"access_token":"eb51eff0b4d85cda1eb1d312c5b6a3b8"

Next, John requests a token as grant_type=password&username=john&password=john123&scope=news_


read news_write . As john has both roles assigned, the token will bear both the requested scopes and the
response will be similar to the following:

"scope":"news_read news_write", "token_type":"bearer", "expires_in":3299,


"refresh_token":"4ca244fb321bd555bd3d555df39315",
"access_token":"42a377a0101877d1d9e29c5f30857e"

This means that Tom can only access the GET operation of the API while John can access both as he is assigned
to both the employee and manager roles. If Tom tries to access the POST operation, there will be an HTTP 403
Forbidden error as follows:

Copyright © WSO2 Inc. 2014-2017 15


WSO2 API Cloud

<ams:fault xmlns:ams="http://wso2.org/apimanager/security">
<ams:code>900910</ams:code>
<ams:message>The access token does not allow you to access the
requested resource</ams:message>
<ams:description>Access failure for API: /orgnews, version: 1.0.0
with key: eb51eff0b4d85cda1eb1d312c5b6a3b8
</ams:description>
</ams:fault>

Endpoints

An endpoint is a specific destination for a message such as an address, WSDL, a failover group, a load-balance
group etc.

WSO2 API Manager has support for a range of different endpoint types, allowing the API Gateway to connect with
advanced types of backends. It supports HTTP endpoints, URL endpoints (also termed as address endpoint), WSDL
endpoints, Failover endpoints, Load-balanced endpoints. For more information about endpoints and how to add, edit
or delete them, see the WSO2 ESB documentation.

Note the following:

You can expose both REST and SOAP services to consumers through APIs.
You cannot call backend services secured with OAuth through APIs created in the API Publisher. At the
moment, you can call only services secured with username/password.
The system reads gateway endpoints from the api-manager.xml file. When there are multiple gateway
environments defined, it picks the gateway endpoint of the production environment. You can define both
HTTP and HTTPS gateway endpoints as follows:

<GatewayEndpoint>http://${carbon.local.ip}:${http.nio.port},https://${carbon.loc
al.ip}:${https.nio.port}</GatewayEndpoint>

If both types of endpoints are defined, the HTTPS endpoint will be picked as the server endpoint.

Sequences

The API Cloud has a default mediation flow that is executed in each API invocation. There are 3 default sequences
engaged as in , out and fault .

Mediators

Sometimes, the backend implementation of a Web service does not exactly match your desired API design. In that
case, you do various message transformations and orchestrate multiple backend services to achieve the design you
want.

The API Cloud comes with a powerful mediation engine that can transform and orchestrate API calls on the fly. It is
built on the WSO2 ESB and supports a variety of mediators that you can use as building blocks for your sequences.
Given below is the list of mediators supported in the API Cloud:

Click to read more...

Category Mediator Description

Copyright © WSO2 Inc. 2014-2017 16


WSO2 API Cloud

Core Call Invokes a service in non-blocking, synchronous manner.

Sequence Inserts a reference to a sequence.

Drop Drops a message.

Enrich Enriches a message.

Property Sets or removes properties associated with the message.

Log Logs a message.

Filter Filter Filters a message using XPath, if-else type of logic.

Validate Validates XML messages against a specified schema.

Switch Filters messages using XPath and switch logic.

ConditionalRouter Implements complex routing rules (header-based routing, content-based routing


and other rules).

Transform XSLT Performs XSLT transformations on the XML payload.

FastXSLT Performs XSLT transformations on the message stream.

URLRewrite Modifies and rewrites URLs or URL fragments.

XQuery Performs XQuery transformation.

Header Sets or removes SOAP headers.

Fault (also called Creates SOAP Faults.


Makefault)

PayloadFactory Transforms or replaces message content in between the client and the backend
server.

Advanced Cache Evaluates messages based on whether the same message came to the ESB.

ForEach Splits a message into a number of different messages by finding matching


elements in an XPath expression of the original message.

Clone Clones a message.

Iterate Splits a message.

Copyright © WSO2 Inc. 2014-2017 17


WSO2 API Cloud

Aggregate Combines a message.

Callout Blocks Web service calls.

Transaction Executes a set of mediators transactionally.

DBReport Writes data to the database.

DBLookup Retrieves information from the database.

Entitlement Evaluates user actions against a XACML policy.

Extension Class Creates and executes a custom mediator.

Script Executes a mediator written in Scripting language.

Also see the list of WSO2 ESB Mediators .

You can extend the API Gateway's default mediation flow to do custom mediation by providing an extension as a
synapse mediation sequence. You design all sequences using a tool like WSO2 Developer Studio and then store
the sequence in the Gateway's registry. See Change the Default Mediation Flow of API Requests.

Response caching

Response caching stores the response messages per each API in a cache. It improves performance because the
backend server does not have to process the same data for a request multiple times. To offset the risk of stale data
in the cache, you can set a time period after which the cache is cleared periodically.

Response caching is automatically disabled in the Cloud. You can enable it when creating a new API or editing an
existing API. Go to the API's Manage tab in the API Publisher, and select Enable from the Response Caching dro
p-down list and give a time-out period.

Copyright © WSO2 Inc. 2014-2017 18


WSO2 API Cloud

Gateway caching

When an API call hits the API Gateway, the Gateway carries out security checks to verify if the token is valid. During
these verifications, the API Gateway extracts parameters such as access token, API and API version that are
passed to it. Since all traffic to APIs goes through the API Gateway, this verification process can become an
overhead if the API name, version and other validation information are not cached. Therefore, caching is enabled at
the Gateway by default.

When caching is enabled and a request hits the Gateway, it first populates the cached entry for a given token. If a
cache entry does not exist in cache, it calls the key manager server. This process is carried out using Web service
calls. Once the key manager server returns the validation information, it gets stored in the Gateway. Because the
API Gateway issues a Web service call to the key manager server only if it does not have a cache entry, the number
of Web service calls to the key manager server is reduced.

Copyright © WSO2 Inc. 2014-2017 19


WSO2 API Cloud

Tutorials
If you are a beginner, look under the Getting Started section:

Getting Started
API Publishing
Backend Integration
Developer Portal
Policies and Monetization
User Management

Getting Started
How do I...

Create and Publish an API


Subscribe to and Invoke an API
Invoke an API using cURL

Create and Publish an API

API creation is the process of linking an existing backend API implementation to the API Publisher so that you can
manage and monitor the API's lifecycle, documentation, security, community, and subscriptions. Alternatively, you
can provide the API implementation in-line in the API Publisher itself.

In this tutorial , you create an API using a production endpoint and publish it to the API Store.

Click the following topics for a description of the concepts that you need to know when creating an API:

API visibility
Resources
Endpoints
Throttling tiers
Sequences
Response caching

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. If you have not registered to the API Cloud yet, go to https://cloud.wso2.com/ and sign up.
2. Log in to the API Cloud and the API Publisher Web application will open automatically.
3. Close the interactive tutorial that starts automatically if you are a first-time user, and then click New API...

Copyright © WSO2 Inc. 2014-2017 20


WSO2 API Cloud

4. Select the option to design a new API and click Start Creating .

5. Give the information in the table below and click Add to add the resource.

Field Sample value

Name PhoneVerification

Context /phoneverify

Tip: You can define the API's version as a parameter of its context by adding the {ve
rsion} into the context. For example, {version}/phoneverify. The API
Manager assigns the actual version of the API to the {version} parameter
internally. For example, https://gateway.api.cloud.wso2.com:8243/t/companyn/1.0.0/p
honeverify. Note that the version appears before the context, allowing you to group
your APIs based on to versions.

Version 1.0.0

Visibility Public

Resources URL Pattern: CheckPhoneNumber


Request Types: GET, POST

Copyright © WSO2 Inc. 2014-2017 21


WSO2 API Cloud

6. After you add the resource, click its GET method to expand it, add the following parameters. You use them to
invoke the API using our integrated API Console, which is explained in later tutorials. Once done, click Imple
ment.

Parameter Description Parameter Data Required


Name Type Type

PhoneNumber Give the phone number to be validated Query String True

LicenseKey Give the license key as 0 for testing Query String True
purpose

Copyright © WSO2 Inc. 2014-2017 22


WSO2 API Cloud

Alternatively, click Save to save all the changes made to the API. You can come back later to edit it further by
selecting the API and clicking on Edit. For details about the states of the API see Manage the API Lifecycle.
7. C l i c k the Managed API option.

8. The Implement tab opens. Enter the information in the table below.

Field Sample value

Endpoint HTTP/REST Endpoint


type

Production This sample service has two operations as CheckPhoneNumber and CheckPhoneNumbe
endpoint rs. Let's use CheckPhoneNumber here.
http://ws.cdyne.com/phoneverify/phoneverify.asmx

To verify the URL, click the Test button next to it.

Copyright © WSO2 Inc. 2014-2017 23


WSO2 API Cloud

9. Click Manage to go to the Manage tab and enter the information in the table below.

Field Sample Description


value

Tier Select The API can be available at different levels of service. They allow you to limit the
Availability all number of successful hits to an API during a given period of time.

Copyright © WSO2 Inc. 2014-2017 24


WSO2 API Cloud

10. Click Save & Publish. This will publish the API that you just created in the API Store so that subscribers can
use it. You can save the API without publishing it. Select the API and click the Lifecycle tab to manage the
API Lifecycle.

Copyright © WSO2 Inc. 2014-2017 25


WSO2 API Cloud

You have created an API.

For details on creating APIs using Swagger definitions, see Create APIs using a Swagger URL.

Subscribe to and Invoke an API

You subscribe to API using the API Store. WSO2 API Store has an integrated Swagger Console, which is part of
the Swagger project. You can use it to invoke APIs and write interactive API documentation.

In this tutorial, you subscribe to an API and invoke it using the integrated API Console. The examples
here use the PhoneVerification API, which is created in section Create and Publish an API.

See the following topics for a description of the concepts that you need to know when invoking an API:

Swagger API Console


Applications
Throttling
Access tokens

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1.

Copyright © WSO2 Inc. 2014-2017 26


WSO2 API Cloud

1. Log in to the API Cloud.

2. In the WSO2 API Publisher, click an API (e.g., PhoneVerification 1.0.0) to open it.

3. Click the View in Store link that appears in the Overview tab of the API. You can also go to the API Store
using the URL http://<hostname>/Store/?tenant=<tenant_name> .

Copyright © WSO2 Inc. 2014-2017 27


WSO2 API Cloud

4. Note the subscription options on the right-hand side of the page that opens. Select the default application, the
Bronze tier and subscribe to the API.

5. W h e n prompted, choose to view subscriptions.

Copyright © WSO2 Inc. 2014-2017 28


WSO2 API Cloud

6. The details of the application that you used to subscribe to the API open. Click the Production Keys tab and
c l i c k G e n e r a t e k e y s .

7. After the keys are generated, click the APIs menu in the API Store and then click the API that you want to
i n v o k e .

Copyright © WSO2 Inc. 2014-2017 29


WSO2 API Cloud

8. W h e n the API opens, click its API Console tab.

9. Expand the GET method, provide the required parameters and click Try it Out. For example,

PhoneNumber E.g., 18006785432

LicenseKey Give 0 for testing purpose

Copyright © WSO2 Inc. 2014-2017 30


WSO2 API Cloud

Authorization The API console is automatically populated by the access token that you generated in
step 6 after subscribing to the API.
The token is prefixed by the string "Bearer" as per the OAuth bearer token profile. OAuth
security is enforced on all published APIs. If the application key is invalid, you get a 401
Unauthorized response in return.

Base URL Appears at the bottom of the console. Using the base URL and the parameters, the
system creates the API URL.

If you cannot invoke the API's HTTPS endpoint (causes the SSLPeerUnverifi
ed exception), it could be because the security certificate issued by the server is
not trusted by your browser. To resolve this issue, access the HTTPS endpoint
directly from your browser and accept the security certificate.

10. Note the response for the API invocation. As we used a valid phone number in this example, the response is
v a l i d .

Copyright © WSO2 Inc. 2014-2017 31


WSO2 API Cloud

You have invoked an API using the Swagger API console.

Invoke an API using cURL

The API Store has an integrated API Console using which you can read API documentation and invoke APIs.
Alternatively, you can use a tool like cURL to invoke APIs.

In this tutorial, you invoke an API using cURL, the open source command-line tool and library for
transferring data. The examples here use the PhoneVerification API, which is created in section Cre
ate and Publish an API.

See the following topics for a description of the concepts that you need to know when invoking to an API:

API visibility and subscription availability


Applications
Application-level throttling
Access tokens

Let's get started.

Copyright © WSO2 Inc. 2014-2017 32


WSO2 API Cloud

1. Log in to the API Store using the URL http://<hostname>/Store?tenant=<tenant_name> and click
the API that you want to subscribe to.

2. Click the APPLICATIONS menu and click ADD APPLICATION to create a new application.

3. Give a name and a tier for the application and click Add.

4. Go back to the API's subscription options and select the application you just created, the Bronze tier, and
c l i c k S u b s c r i b e .

Copyright © WSO2 Inc. 2014-2017 33


WSO2 API Cloud

5. When prompted, choose to view subscriptions. Then, go to the Production Keys tab and click Generate
keys.

You can set a token validity period in the given text box. By default, it is set to one hour. If you set a
minus value (e.g., -1), the token will never expire.

Let's invoke the API that you just subscribed to.

6. Install cURL if it is not there in your environment. Note that cURL comes by default in some operating

Copyright © WSO2 Inc. 2014-2017 34


WSO2 API Cloud
6.

systems. You can also use any other REST client.

7. Open the command line and execute the following cURL command:

curl -k -H "Authorization: Bearer <access token>" -v '<API URL>'

Be sure to replace the placeholders as follows:

<access token>: Give the token generated in step 6


<API URL>: Click the APIs menu, click the API you want to invoke and then copy the production URL
in the API's Overview tab.

Then, append the payload to the production URL. E.g., https://gateway.api.cloud.wso2.com


:443/t/companyn3/phoneverify/1.0.0/CheckPhoneNumber?PhoneNumber=18006785432
&LicenseKey=0.

Here's an example:

curl -k -H "Authorization: Bearer


1fa22cef-c791-3105-9ac4-58511c199aa0"
'https://gateway.api.cloud.wso2.com:443/t/companyn3/phoneverify/1.0.0
/CheckPhoneNumber?PhoneNumber=18006785432&LicenseKey=0'

8. Note the result that appears on the command line.

9. Similarly, invoke the POST method using the following cURL command:

curl -k -H "Authorization: Bearer


1fa22cef-c791-3105-9ac4-58511c199aa0" --data
"PhoneNumber=18006785432&LicenseKey=0"
https://gateway.api.cloud.wso2.com:443/t/companyn3/phoneverify/1.0.0/
CheckPhoneNumber

In this tutorial, you subscribed to an API and invoked it using cURL.

API Publishing

Copyright © WSO2 Inc. 2014-2017 35


WSO2 API Cloud

How do I...

Add API Documentation


Change the Default Mediation Flow of API Requests
Convert a JSON Message to SOAP and SOAP to JSON
Create APIs using a Swagger URL
Create a Prototyped API with an Inline Script
Manage the API Lifecycle
Migrate your APIs between Environments
Publish and Invoke a SOAP API

Add API Documentation

API documentation helps API subscribers to understand the functionality of the API, and API publishers to market
APIs and sustain competition. Using the API Publisher, you can add different types of documentation from different
sources. All documents created in the API Publisher have unique URLs to help improve SEO support.

In this tutorial, you add in-line, URL-based and file-based documentation to your API and then view it in
the API Store. The examples here use the PhoneVerification API, which is created in section Create
and Publish an API.

The documentation types supported in the API Publisher are as follows:

In-line
URL-based
File-based
Swagger documentation: The API Publisher has integrated Swagger to facilitate simple, interactive
API documentation and invocation.

See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

In-line documentation
Documentation using a URL
Documentation using a file

1. Log in to WSO2 API Cloud and the API Publisher opens.


2. Click the API to which you want to add documentation (e.g., PhoneVerification 1.0.0).

Copyright © WSO2 Inc. 2014-2017 36


WSO2 API Cloud

3. Select the Docs tab of the API and click the Add New Document link.

In-line documentation

Allows you to host documentation (How-tos, Samples, SDK, forums etc.) in the API Publisher itself and allows

Copyright © WSO2 Inc. 2014-2017 37


WSO2 API Cloud

it to be edited directly from the UI.

4. Provide the following details to create a doc In-line.

Name PhoneVerification

Type How To

Source In-line

Summary Check the validity of a phone number

5. Click the Add Document button.


6. After adding the document, click the Edit Content link associated with it.

7.

Copyright © WSO2 Inc. 2014-2017 38


WSO2 API Cloud

7. The embedded editor opens allowing you to edit the document's content in-line. Add your content and click S
ave and Close.

8. The API's Doc tab opens. Click the Add New Document link again.

Documentation using a URL

This option allows you to link to file references (URLs) of an external configuration management system.

9. Then provide the following information to create another doc using a URL.

Name CDYNE Wiki

Type Other (specify)

Source URL:
http://wiki.cdyne.com/index.php/Phone_Verification

Summary
CDYNE Phone Verification API

Copyright © WSO2 Inc. 2014-2017 39


WSO2 API Cloud

10. Click the Add Document button.


11. The API's Doc tab opens again. Click the Add New Document link again to add yet another document using
a file.

Documentation using a file

This option allows you to upload the documentation directly to the server as a file.

12. Enter the following information:

Name API Manager Samples

Type Samples & SDK

Source You can provide any file format (common formats are PDF, HTML, .doc, text) of any size. For
example, use the sample PDF file here.

Copyright © WSO2 Inc. 2014-2017 40


WSO2 API Cloud

13. After adding the details, click the Add Document button.
You have now added three documents to the API: in-line, using a URL and a file.

14. Log in to the API Store and click the PhoneVerification 1.0.0 API.

Copyright © WSO2 Inc. 2014-2017 41


WSO2 API Cloud

In the API Store, as a subscriber, you can read the doc and learn about the API.
15. Go to the API's Documentation tab and see the documents listed by type. Expand the categories and click
the View Content or Download links to see the documentation content.

Copyright © WSO2 Inc. 2014-2017 42


WSO2 API Cloud

You have created documentation using the API Publisher and viewed it as a subscriber in the API Store.

Change the Default Mediation Flow of API Requests

Sometimes, the backend implementation of a web service does not exactly match your desired API design. In that
case, you do various message transformations and orchestrate multiple backend services to achieve the design you
want.

In this tutorial, you create a custom sequence using the WSO2 Tooling Plug-in and use it in your APIs
to mediate the incoming API calls.

The API Cloud comes with a powerful mediation engine that can transform and orchestrate API calls on the

Copyright © WSO2 Inc. 2014-2017 43


WSO2 API Cloud

fly. It is built on WSO2 ESB and supports a variety of mediators that you can use as building blocks for your
sequences. See the list of mediators supported in the API Cloud and WSO2 ESB.

You can extend the API Gateway's default mediation flow to do custom mediation by providing an extension
as a synapse mediation sequence. You need to design all sequences using a tool like the WSO2 Tooling
Plug-in and then store the sequence in the Gateway's registry.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. L o g in to the API Publisher.


https://api.cloud.wso2.com/publisher/

2. Click Add New API, Design a new API, and Start creating to create an API with the following information
and then click Implement.

Field Sample value

Name YahooWeather

Context /weather

Version 1.0

Resources URL current/{country}/{zipcode}


pattern

Request GET method to return the current weather conditions of a ZIP code that belongs
types to a particular country

Copyright © WSO2 Inc. 2014-2017 44


WSO2 API Cloud

The Implement tab opens.

3. Select Managed API, provide the information given in the table below and click Next: Manage >.

Field Sample value

Endpoint HTTP/REST endpoint


type

Production You can find the Yahoo weather API's endpoint from https://developer.yahoo.com/weather/.
endpoint Copy the part before the '?' sign to get this URL: https://query.yahooapis.com/v1/public/yql

To verify the URL, click the Test button next to it.

Copyright © WSO2 Inc. 2014-2017 45


WSO2 API Cloud

Sandbox https://query.yahooapis.com/v1/public/yql. To verify the URL, click the Test button next to it.
endpoint

4. Provide the following information in the Manage tab and click Save & Publish once you are done.

Field Sample value

Tier Availability Gold

Keep the default values for the other attributes

Copyright © WSO2 Inc. 2014-2017 46


WSO2 API Cloud

5. Download and install the WSO2 API Manager Tooling Plug-in if you have not done so already. Start Eclipse
by double clicking on the Eclipse application, which is inside the downloaded folder.

6. On the Window menu click Perspective, Open Perspective, Other to open the Eclipse perspective
selection window.

7. On the dialog box that appears, click WSO2 API Manager and click OK.

Copyright © WSO2 Inc. 2014-2017 47


7. WSO2 API Cloud

8. On the APIM perspective, click the Login icon as shown below.

9. Enter your cloud username (in the format <email@company_name>) and password, and click OK in
the dialog box that appears.

10. On the tree view that appears, expand the folder structure of the existing API.
11. Right-click on the in sequence folder and click Create to create a new in sequence.

Copyright © WSO2 Inc. 2014-2017 48


WSO2 API Cloud
11.

This is because you want the custom sequence to be invoked in the In direction or the request path.
If you want it to be involved in the Out or Fault paths, select the respective folder under customsequence
s.

Tip : If you prefer not to use the registry to upload the sequence or want to engage a sequence to all
APIs in WSO2 API-M at once, you can do so by saving the mediation sequence XML file in the file
system. See Adding Mediation Extensions for details.

12. Name the sequence YahooWeatherSequence.


13. Your sequence now appears on the Developer Studio console. From under the Mediators section, drag and
drop a Property mediator to your sequence and give the following values to the property mediator.

Property New Property


Name

New YQL
Property
Name

Value Expression
Type

Value For the XPath expression, we take a part of the query in the Yahoo API's endpoint (https://developer.yahoo
Expression

concat('?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(s

Copyright © WSO2 Inc. 2014-2017 49


WSO2 API Cloud

14. Similarly, add another property mediator with the following values.
This is an HTTP transport property that appends its value to the address endpoint URL. Once you are done,
save the sequence.

Property Name New Property

New Property Name REST_URL_POSTFIX

Value Type Expression

Value Expression get-property('YQL')

Property Scope Axis2

Copyright © WSO2 Inc. 2014-2017 50


WSO2 API Cloud

15. Navigate to the File menu, and click Save to save the sequence.
16. Right-click on the sequence and click Commit File, and thereafter click Yes to push the changes to the
Publisher server.
17. Sign in to WSO2 API Publisher again, search for the API that you created earlier, and click the Edit link to go
to the edit wizard.
18. Click Implement and Manage API. Thereafter, click the Enable Message Mediation checkbox, and select
the sequence that you created for the In flow. Next, Save the API.

Tip : It might take a few minutes for the sequence to be uploaded into the API Publisher. If it isn't
there, please check again later.

Copyright © WSO2 Inc. 2014-2017 51


WSO2 API Cloud

When selecting a mediator, make sure that it is a non-blocking mediator as blocking mediators are
not supported in API Gateway custom mediations. For more details, see Adding Mediation
Extensions.

19. Sign in to the API Store, subscribe to the API that you just published and generate the access tokens in order
to invoke the API.

20. Click the API Console tab of the API. It opens the integrated API Console using which you can invoke the
API.

Copyright © WSO2 Inc. 2014-2017 52


WSO2 API Cloud

21. Give the following values for the parameters and invoke the API. You can also give any other value of your
choice.

country usa

zipcode 95004

22. Note the response that you get as a JSON object from Yahoo.

{
"query": {
"count": 1,
"created": "2017-05-04T12:49:03Z",
"lang": "en-US",
"results": {
"channel": {
"units": {
"distance": "mi",
"pressure": "in",
"speed": "mph",
"temperature": "F"
},

Copyright © WSO2 Inc. 2014-2017 53


WSO2 API Cloud

"title": "Yahoo! Weather - Aromas, CA, US",


"link":
"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https
://weather.yahoo.com/country/state/city-12797499/",
"description": "Yahoo! Weather for Aromas, CA, US",
"language": "en-us",
"lastBuildDate": "Thu, 04 May 2017 05:49 AM PDT",
"ttl": "60",
"location": {
"city": "Aromas",
"country": "United States",
"region": " CA"
},
"wind": {
"chill": "50",
"direction": "245",
"speed": "4"
},
"atmosphere": {
"humidity": "98",
"pressure": "999.0",
"rising": "0",
"visibility": "7.5"
},
"astronomy": {
"sunrise": "6:9 am",
"sunset": "7:58 pm"
},
"image": {
"title": "Yahoo! Weather",
"width": "142",
"height": "18",
"link": "http://weather.yahoo.com",
"url":
"http://l.yimg.com/a/i/brand/purplelogo//uh/us/news-wea.gif"
},
"item": {
"title": "Conditions for Aromas, CA, US at 05:00 AM PDT",
"lat": "36.878021",
"long": "-121.618973",
"link":
"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/*https
://weather.yahoo.com/country/state/city-12797499/",
"pubDate": "Thu, 04 May 2017 05:00 AM PDT",
"condition": {
"code": "33",
"date": "Thu, 04 May 2017 05:00 AM PDT",
"temp": "51",
"text": "Mostly Clear"
},
"forecast": [
{
"code": "30",

Copyright © WSO2 Inc. 2014-2017 54


WSO2 API Cloud

"date": "04 May 2017",


"day": "Thu",
"high": "74",
"low": "55",
"text": "Partly Cloudy"
},
{
"code": "28",
"date": "05 May 2017",
"day": "Fri",
"high": "71",
"low": "53",
"text": "Mostly Cloudy"
},
{
"code": "30",
"date": "06 May 2017",
"day": "Sat",
"high": "65",
"low": "47",
"text": "Partly Cloudy"
},
{
"code": "12",
"date": "07 May 2017",
"day": "Sun",
"high": "62",
"low": "48",
"text": "Rain"
},
{
"code": "30",
"date": "08 May 2017",
"day": "Mon",
"high": "69",
"low": "46",
"text": "Partly Cloudy"
},
{
"code": "30",
"date": "09 May 2017",
"day": "Tue",
"high": "69",
"low": "48",
"text": "Partly Cloudy"
},
{
"code": "28",
"date": "10 May 2017",
"day": "Wed",
"high": "70",
"low": "52",
"text": "Mostly Cloudy"

Copyright © WSO2 Inc. 2014-2017 55


WSO2 API Cloud

},
{
"code": "30",
"date": "11 May 2017",
"day": "Thu",
"high": "72",
"low": "52",
"text": "Partly Cloudy"
},
{
"code": "30",
"date": "12 May 2017",
"day": "Fri",
"high": "72",
"low": "48",
"text": "Partly Cloudy"
},
{
"code": "34",
"date": "13 May 2017",
"day": "Sat",
"high": "71",
"low": "46",
"text": "Mostly Sunny"
}
],
"description": "<![CDATA[<img
src=\"http://l.yimg.com/a/i/us/we/52/33.gif\"/>\n<BR />\n<b>Current
Conditions:</b>\n<BR />Mostly Clear\n<BR />\n<BR
/>\n<b>Forecast:</b>\n<BR /> Thu - Partly Cloudy. High: 74Low: 55\n<BR
/> Fri - Mostly Cloudy. High: 71Low: 53\n<BR /> Sat - Partly Cloudy.
High: 65Low: 47\n<BR /> Sun - Rain. High: 62Low: 48\n<BR /> Mon -
Partly Cloudy. High: 69Low: 46\n<BR />\n<BR />\n<a
href=\"http://us.rd.yahoo.com/dailynews/rss/weather/Country__Country/
*https://weather.yahoo.com/country/state/city-12797499/\">Full
Forecast at Yahoo! Weather</a>\n<BR />\n<BR />\n(provided by <a
href=\"http://www.weather.com\" >The Weather Channel</a>)\n<BR
/>\n]]>",
"guid": {
"isPermaLink": "false"
}
}
}

Copyright © WSO2 Inc. 2014-2017 56


WSO2 API Cloud

}
}
}

In this tutorial, you created a sequence to change the default mediation flow of API requests, deployed it in the API
Gateway and invoked an API using the custom mediation flow.

Convert a JSON Message to SOAP and SOAP to JSON

The API Cloud comes with a powerful mediation engine that can transform and orchestrate API calls on the fly. It is
built on the WSO2 ESB and supports a variety of mediators that you can use as building blocks for your sequences.
See the list of mediators supported in the API Cloud and WSO2 ESB.

You can provide an extension as a synapse mediation sequence to the API Gateway's default mediation flow to
transform message formats.

In this tutorial, you convert a request message with a JSON payload and a REST URL to a SOAP
message, send it to the backend and then convert the request from the backend to JSON.

The examples here use the PhoneVerification API, which is created in Create and Publish an API. If
you do not have this API or the existing one is deprecated, simply create a new API with the backend as
http://ws.cdyne.com/phoneverify/phoneverify.asmx. It accepts both SOAP and REST requests as shown
here.

Let's get started.

1. Log in to the API Publisher and click the edit icon of the PhoneVerification API.

Copyright © WSO2 Inc. 2014-2017 57


WSO2 API Cloud

2. Add the following resource to the API.

Tip: The resource you create here invokes the SOAP 1.2 Web service of the backend. Therefore, the
recommended method is HTTP POST. As you do not include the payload in a query string, avoid
giving any specific name in the URL pattern, which will be amended to the actual backend URL.

Field Sample value

Resources URL pattern: /*

Request types: POST

3. After the resource is added, expand it and note a parameter by the name payload already available. You can
use this parameter to pass the payload to the backend. Edit its values as follows:

Parameter name Description Parameter Type Data Type Required

Copyright © WSO2 Inc. 2014-2017 58


WSO2 API Cloud

payload Pass the phone number and license key body String True

Next, let's write a sequence to convert the JSON payload to a SOAP request. We do this because the
backend accepts SOAP requests.

4. Navigate to the Implement page and change the endpoint of the API to http://ws.cdyne.com/phoneverify/pho
neverify.asmx?WSDL . Once the edits are done, click Save .

5. Download and install the WSO2 API Manager Tooling Plug-in if you have not done so already. Open Eclipse
by double clicking the Eclipse.app file inside the downloaded folder.

6. Click Window > Open Perspective > Other to open the Eclipse perspective selection window. Alternatively,
click the Open Perspective icon in the top, right-hand corner.

Copyright © WSO2 Inc. 2014-2017 59


6. WSO2 API Cloud

7. Click the Developer Studio menu and choose Open Dashboard. When the dashboard opens, click the ESB
Config Project link.

8. Create a new ESB project by the name PhoneProject.

Copyright © WSO2 Inc. 2014-2017 60


WSO2 API Cloud

9. Click the Sequence link on the Developer Studio Dashboard and create a new sequence by the name JSONt
oSOAP in the PhoneProject.

Copyright © WSO2 Inc. 2014-2017 61


WSO2 API Cloud

10. Your sequence now appears on the Developer Studio console. From under the Mediators section, drag and
drop a PayloadFactory mediator to your sequence and give the following values to the mediator.

Tip: The PayloadFactory mediator transforms the content of your message. The <args> elements
define arguments that retrieve values at runtime by evaluating the provided expression against the
SOAP body. You can configure the format of the request/response and map it to the arguments.

For example, in the following configuration, the values for the format parameters PhoneNumber and
LicenseKey will be assigned with values that are taken from the <args> elements (arguments,) in
that particular order.

For details on how you got this configuration, see PayloadFactory Mediator in the WSO2 ESB
documentation.

Copyright © WSO2 Inc. 2014-2017 62


WSO2 API Cloud

Payload
<soap12:Envelope
xmlns:xsi="http://www.w3.or
g/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.or
g/2001/XMLSchema"
xmlns:soap12="http://www.w3
.org/2003/05/soap-envelope"
>
<soap12:Body>
<CheckPhoneNumber
xmlns="http://ws.cdyne.com/
PhoneVerify/query">

<PhoneNumber>$1</PhoneNumbe
r>

<LicenseKey>$2</LicenseKey>
</CheckPhoneNumber>
</soap12:Body>
</soap12:Envelope>

Copyright © WSO2 Inc. 2014-2017 63


WSO2 API Cloud

Args Give the following arguments:

Type Value Evaluator

expression //request/PhoneNumber xml

expression //request/LicenseKey xml

11. Similarly, add a property mediator to the same sequence and give the following values to the property
m e d i a t o r .

Property Name messageType

Value Type Literal

Value application/soap+xml

Property Scope axis2

12. Save the sequence, which is in XML format (e.g., JSONtoSOAP.xml). This will be the In sequence for your
API.

13. Go back to the Developer Studio Dashboard, click the Sequence link and create another sequence by the

Copyright © WSO2 Inc. 2014-2017 64


WSO2 API Cloud

13.
name SOAPtoJSON in the PhoneProject.

14. Add a property mediator to the second sequence and give the following values to the property mediator.

Property Name messageType

Value Type Literal

Value application/json

Property Scope axis2

Copyright © WSO2 Inc. 2014-2017 65


WSO2 API Cloud

15. Save the sequence, which is in XML format (e.g., SOAPtoJSON.xml). This will be the Out sequence for your
API.

16. Log in to the API Gateway's management console using the URL https://gateway.api.cloud.wso2.com/carbon
/admin/login.jsp. Copy your username from the top right-hand corner of the API Publisher. Use the same
password that you used to log in to WSO2 Cloud.

17. After logging in, click the Browse menu under the Resources menu.

Copyright © WSO2 Inc. 2014-2017 66


WSO2 API Cloud

18. When the API Gateway's registry opens, navigate to the registry path /_system/governance/apimgt/cu
stomsequences/in. This is because you want the custom sequence to be invoked in the In direction or the
request path.

19. Click Add Resource and upload the XML file of the sequence that you created earlier.

Copyright © WSO2 Inc. 2014-2017 67


WSO2 API Cloud

Next, let's write another sequence to convert the SOAP response that the backend sends to JSON.

20. Similarly, navigate to the registry path /_system/governance/apimgt/customsequences/out and


upload the SOAPtoJSON.xml sequence file. This will invoke the second sequence in the Out direction or the
response path.

Copyright © WSO2 Inc. 2014-2017 68


WSO2 API Cloud

21. Log back to the API Publisher, click the Edit link associated with the API, navigate to the Implement tab,
click the Enable Message Mediation checkbox and engage the In and out sequences that you created
earlier.

Copyright © WSO2 Inc. 2014-2017 69


WSO2 API Cloud

22. Save the API.


You have created an API, a resource to access the SOAP backend and engaged sequences to the request
and response paths to convert the message format from JSON to SOAP and back to JSON. Let's subscribe
to the API and invoke it.
23. Log in to the API Store and subscribe to the API and create an access token if you have not done so already.

24. Go to the API Console tab and expand the POST method.

25. Give the payload in the body parameter in JSON format and click Try it out. Here's a sample JSON
payload: {"request":{"PhoneNumber":"18006785432","LicenseKey":"0"}}

Copyright © WSO2 Inc. 2014-2017 70


WSO2 API Cloud

26. Note that you get a JSON response to the JSON request whereas the backend accepts SOAP messages.
The request and response are converted by the sequences that you engaged at the API Gateway.

In this tutorial, you converted a message from JSON to SOAP and back to JSON using In and Out sequences.

Copyright © WSO2 Inc. 2014-2017 71


WSO2 API Cloud

Create APIs using a Swagger URL

You can use publicly hosted Swagger files to create APIs using WSO2 API Cloud. There are 2 methods to create an
API using a Swagger file.

Only Swagger 2.0 file format is supported. If your file is of an earlier version, please upgrade it prior to using
it in WSO2 API Cloud.

Designing a new API with a Swagger File


Create a new API using and existing API definition

Designing a new API with a Swagger File

The steps below show how to create an API using a Swagger file.

1. Log in to the API Cloud and the API Publisher will open automatically. Start creating an API by selecting Desi
gn new API and clicking Start Creating.

2. In API Definition click Import to import all the associated methods and parameters.

3. In the dialog box that appears, select Swagger URL. Paste the URL given below and click Import.
Sample URL : https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/pets
tore-simple.json

Copyright © WSO2 Inc. 2014-2017 72


WSO2 API Cloud

4. Give the information in the table below.

Field Sample Value

Name PetStoreAPI

Context /petstore

Version 1.0.0

Visibility Public

5. Continue on to the Manage section to edit, save and/or publish the API.

Create a new API using and existing API definition

If you already have an existing API you can use the Swagger definition to replicate it.

1. Go to Add New API and select I have an existing API.


2. In the dropdown section, select Swagger URL and paste the URL of your hosted Swagger definition.
3. Click Start Creating to proceed to the next step. You can also upload a Swagger file instead of the URL.

For more details on creating and publishing APIs on WSO2 API Cloud, see Create and Publish an API.

Create a Prototyped API with an Inline Script

Copyright © WSO2 Inc. 2014-2017 73


WSO2 API Cloud

A prototype is an early implementation of an API that you create with an inline script and then make available for
testing purpose and to collect feedback from subscribers while you work on a proper, long-term implementation.

In this tutorial, you create an API prototype with an inline JavaScript code, deploy it and invoke it using
the API Console integrated in the API Store.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. Log in to the API Publisher.


2. Select the option to design a new API and click Start Creating.

3. In the page that opens, enter the information given in the table below. To add resources, click the Add button.

Name SuperPhone

Context /superphone

Version 1.0.0

Resources URL pattern: CheckPhoneNumber/{PhoneNumber}


Request types: GET

Copyright © WSO2 Inc. 2014-2017 74


WSO2 API Cloud

4. Once the information is added, click Implement to go to the next page.

5. As this is a prototyped API, you do not have an actual backend implementation for it yet. Therefore, in the Pr
ototype sections under the Implement tab, click the implementation method as Inline .

Copyright © WSO2 Inc. 2014-2017 75


WSO2 API Cloud

The default skeleton code generated by the API Cloud reads the PhoneNumber parameter value from the
URL and give it as a JSON output.

6. Expand the GET method. The default skeleton code generated by the API Cloud reads the PhoneNumber pa
rameter value from the URL and give it as a JSON output. Replace the skeleton code with the following,
which produces a realistic XML output that your actual implementation will someday provide.

mc.setProperty('CONTENT_TYPE','application/xml');
var PhoneNumber = mc.getProperty('uri.var.PhoneNumber');
mc.setPayloadJSON({
"PhoneReturn":{
"-xmlns:xsd":"http://www.w3.org/2001/XMLSchema",
"-xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance",
"-xmlns":"http://ws.cdyne.com/PhoneVerify/query",
"Company":"Toll Free",
"Valid":"true",
"Use":"Assigned to a code holder for normal use.",
"State":"TF",
"OriginalNumber":PhoneNumber,
"CleanNumber":PhoneNumber,
"Country":"United States",
"PrefixType":"Landline",
"sms":"Landline",
"TelecomState":"TF",
"Wireless":"false"
}
});

Copyright © WSO2 Inc. 2014-2017 76


WSO2 API Cloud

7. Click the Deploy as a Prototype button at the end of the page to deploy the prototype.

8. When prompted, click the Go to API Store button.

9. The API opens in the API Store. Note that its status is PROTOTYPED .

Let's invoke the API prototype.

Tip: You can invoke prototyped APIs without signing in to the API Store or subscribing to the API.
The purpose of a prototype is advertising and giving an early implementation for users to test.

Copyright © WSO2 Inc. 2014-2017 77


WSO2 API Cloud

10. Go to the API's API Console tab, expand the GET method, give any value for the parameter (say phone
number is 18006785432) and click Try it out.

11. Note the response you get according to the XML pattern you defined in step 6.

You have created an API with inline script, deployed it as a prototype and invoked it through the integrated API
Console.

Manage the API Lifecycle

Copyright © WSO2 Inc. 2014-2017 78


WSO2 API Cloud

These tutorials show how to create, prototype, publish, deprecate and retire APIs. See the video tutorial here or a
step-by-step walk-through of the video tutorial below.

See these sections for a step-by-step walk-though of the video tutorial:

Create a new API Version


Deploy and Test as a Prototype
Publish the new Version and Deprecate the old

Create a new API Version

A new API version is created when you want to change a published API's behavior, authentication mechanism,
resources, throttling tiers, target audiences etc. It isn't recommended to modify a published API that has subscribers
plugged to it.

After creating a new version, you typically deploy it as a prototype for early promotion. A prototype can be used for
testing, without subscription, along with the published versions of the API. After a period of time during which the
new version is used in parallel with the older versions, the prototyped API can be published and its older versions
deprecated.

In this tutorial, you create a new version of an existing API and then edit the new version's functionality.

The examples here use the PhoneVerification API, which is created in section Create and Publish an
API.

A video tutorial of all the tutorials in this section is available here.

The steps below show how to create a new version of an existing API.

1. Log in to the API Publisher.


2. Select the API that you want to create a version of (e.g., PhoneVerification 1.0.0).
3. The API opens. Click CREATE NEW VERSION.

Copyright © WSO2 Inc. 2014-2017 79


WSO2 API Cloud

4. Give a version number, check the default version option, and click Done .

Tip: The Default Version option means that you make this version the default in a group of different
versions of the API. A default API can be invoked without specifying the version number in the URL.
For example, if you mark http://host:port/youtube/2.0 as the default version when the API has 1.0 and
3.0 versions as well, requests made to http://host:port/youtube/ get automatically routed to version
2.0.

If you mark any version of an API as the default, you get two API URLs in its Overview page in the
API Store. One URL is with the version and the other is without. You can invoke a default version
using both URLs.

If you mark an unpublished API as the default, the previous default, published API will still be used as

Copyright © WSO2 Inc. 2014-2017 80


WSO2 API Cloud

the default until the new default API is published (or prototyped).

5. The All APIs page opens. Click the edit icon of the new API version to open it in edit mode.

6. Do the required modifications to the API. For example, assuming that the POST method is redundant, let's
delete it from the resource that we added to the API at the time it was created.

7. Click Save once the edits are done.

You have created a new version of an API. In the next tutorial, you deploy this API as a prototype and test it with its
older versions.

Deploy and Test as a Prototype

Copyright © WSO2 Inc. 2014-2017 81


WSO2 API Cloud

An API prototype is created for the purpose of early promotion and testing. You can deploy a new API or a new
version of an existing API as a prototype. It gives subscribers an early implementation of the API that they can try
out without a subscription or monetization, and provide feedback to improve. After a period of time, publishers can
make changes the users request and publish the API.

In this tutorial, you deploy a new version of an API as a prototype and observe how subscribers can see
it in the API Store and how the prototyped API behaves in the Store.

The examples here use the API PhoneVerification 2.0.0, which is created in the previous tutorial.

A video tutorial of the tutorials in this section is available here.

1. Log in to the API Publisher and select the API (e.g., PhoneVerification 2.0.0) that you want to
prototype.

After creating a new version of an API, you typically deploy it as a prototype for the purpose of testing and
early promotion.
2. Click the Lifecycle tab of the API and click Deploy as a Prototype.

Copyright © WSO2 Inc. 2014-2017 82


WSO2 API Cloud

Tip: You can also prototype an API by going to its edit mode in the API Publisher, then the Implemen
t tab and then clicking Deploy as a Prototype under the Prototyped API section.

3. Log in to the API Store and click the newly prototyped API to open it.

4. The APIs Overview page opens. Note the following:


There are no subscription options.

Copyright © WSO2 Inc. 2014-2017 83


4. WSO2 API Cloud

There are two sets of URLs (with and without the version). This is because you marked the 2.0.0
version as the default version in step 4 of the previous tutorial.
Other features like documentation, social media and forums are available.

5. Click the API Console tab and note that the POST method is not available as we removed that in the new
v e r s i o n .

Copyright © WSO2 Inc. 2014-2017 84


WSO2 API Cloud

Let's invoke the prototyped API.

6. In the API Console of the prototyped API, expand the GET method, give the parameter values (e.g.,
PhoneNumber: 18006785432 and LicenseKey: 0) and invoke the API.

7. Note the response that appears in the console. You do not have to subscribe to the API or pass an
authorization key to invoke a prototyped API.

Copyright © WSO2 Inc. 2014-2017 85


WSO2 API Cloud

8. Similarly, try to invoke the 1.0.0 version of the API without an access token (delete the token that is
automatically populated).

Copyright © WSO2 Inc. 2014-2017 86


WSO2 API Cloud

9. Note that you get an authentication error as "Missing credentials."

You have prototyped an API and tested it along with its older and published versions. In the next tutorial, you publish
the prototyped API and deprecate its older versions.

Publish the new Version and Deprecate the old

You publish an API to make it available for subscription in the API Store. In the API Cloud, your tenant store is
visible to other registered tenants as well. Therefore, users of the other tenants can view the APIs that are published
in your default API Store. This allows you to advertise your APIs to a wider audience. Although the APIs that are
published in your tenant store are visible to the users of other tenant stores, they need to log in to your tenant store
in order to subscribe to and use them.

Copyright © WSO2 Inc. 2014-2017 87


WSO2 API Cloud

In this tutorial, you deprecate an older version of an API and observe how the existing and new
subscribers can interact with a deprecated API.

For a description of the API lifecycle stages, see API lifecycle.

A video tutorial of all the tutorials in this section is available here.

The steps below show how to publish an API to its default API Store:

1. Log in to the API Publisher. If you are not the organization's admin, make sure you have the publisher role
assigned.
2. Click the API that you prototyped in the previous tutorial (e.g., PhoneVerification 2.0.0).

3. Go to the API's Lifecycle tab, click the Deprecate Old Versions check box and click Publish. This will
automatically deprecate version 1.0.0 of the PhoneVerification API.

Tip: You can manually deprecate a published API by going to its Lifecycle tab and clicking the Depre
cate button.

Tip: The Lifecycle tab is only visible to users with publisher privileges.

Copyright © WSO2 Inc. 2014-2017 88


WSO2 API Cloud

Tip: Leave the Require Re-Subscription check box unchecked if you want all users who are
subscribed to the older version of the API to be automatically subscribed to the new version. If not,
they need to subscribe to the new version again.

The API is now published to the default API Store.

4. Go to the API Store and click the APIs menu to see the API now listed under production APIs.

5.

Copyright © WSO2 Inc. 2014-2017 89


WSO2 API Cloud

5. Go back to the API Store, click the APPLICATIONS menu and open DefaultApplication. Click the Subs
criptions tab to see the deprecated API. The subscriptions made to the older API versions must be
d e p r e c a t e d n o w .

Tip: When an API is deprecated, new subscriptions are disabled (you cannot see the subscription
options) and existing subscribers can continue to use the API as usual until it is eventually retired.

You have published a new API version to the API Store and deprecated its previous versions.

Migrate your APIs between Environments

Any user with admin privileges can migrate the APIs from WSO2 API Cloud to another environment and also from
another environment to the API Cloud without having to recreate the APIs.

Migrating your API from the APIM Local Setup to WSO2 API Cloud
Migrating your API from WSO2 API Cloud to a APIM Local Setup

Migrating your API from the APIM Local Setup to WSO2 API Cloud

Any user with admin privileges can migrate the APIs from a local WSO2 API Manager (WSO2 APIM) environment
to WSO2 API Cloud without having to recreate the APIs.

In this tutorial, you set up an instance of WSO2 API Manager in your local environment, create an API
in the API Manager instance and then migrate that API from the local setup to WSO2 API Cloud.

Let's get started!

1. Go to http://wso2.com/products/api-manager/ and download WSO2 API Manager 2.1.0 by clicking the DOWN
LOAD button in the upper right-hand corner.

Tip: To migrate APIs, your local environment must have the same API Manager version that the API
Cloud runs on.

2.

Copyright © WSO2 Inc. 2014-2017 90


WSO2 API Cloud

2. Extract the ZIP file to a suitable location in your machine. Let's call this location <APIM_HOME>.
3. To export the API that you will later create in the API Manager, you need the API Import/Export tool provided
by WSO2. Download this WAR file and copy it to the <APIM_HOME>/repository/deployment/server/
webapps folder. It deploys the API Import/Export tool in your API Manager server.
4. Start the API Manager by executing one of the following commands:
On Windows: <APIM_HOME>\bin\wso2server.bat --run
On Linux/Solaris/Mac OS: sh <APIM_HOME>/bin/wso2server.sh

5. Sign in to the API Publisher in your local environment using the URL http://localhost:9763/publisher and
credentials admin/admin.

6. Create and publish an API with the following details. If you do not know how to create and publish an API,
see Create and Publish an API.

Tab Name Parameters Values

Design Tab Name PhoneTest

Context /phonetest

Version 1.0.0

Visibility Public

API Click Next without entering anything and the system will prompt you to
Definition add a wildcard resource (/*). Click Yes.

Implement Tab Production http://ws.cdyne.com/phoneverify/phoneverify.asmx


-> Managed Endpoint
API

Copyright © WSO2 Inc. 2014-2017 91


WSO2 API Cloud

Manage Tab Tier Gold


Availability
Tip: You cannot import a tier to an environment if it is not
supported there, although it is supported in the source
environment.

For example, the Unlimited tier is supported in WSO2 API


Manager, but not in WSO2 API Cloud. Therefore, you cannot
import it to the Cloud.

You have now set up an instance of API Manager in your local environment and created an API in it. Let's
export the API to a ZIP file.

7. Install cURL in your local machine.


8. Using the command line (if you use a Mac/Linux) or an online Base64 encoder such as https://www.base64e
ncode.org/, create a Base64-encoded string of the credentials of the API Manager, separated by a colon
as <username>:<password>. In this example, it is admin:admin.

If you use Mac/Linux, use the following command.


echo -n <username>:<password> | base64

ex. echo -n admin:admin | base64

Tip: Only users with admin privileges can migrate APIs between environments using the API

Copyright © WSO2 Inc. 2014-2017 92


WSO2 API Cloud

Import/Export tool.

9. Navigate to a suitable location using the command-line or terminal and execute the following cURL command
to export your API as a ZIP file.

curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>"
-X GET
"https://<APIM_HOST:Port>/api-import-export-2.1.0-v2/export-api?name=
<API_Name>&version=<API-Version>
&provider=<API_provider>" -k > <ZIP_File_Name>.zip

According to our example, the command is:


curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>=" -X GET
"https://localhost:9443/api-import-export-2.1.0-v2/export-api?name=Ph
oneTest&version=1.0.0&provider=admin" -k > myExportedAPI.zip

You have exported an API to a ZIP file. Let's import that to your tenant in WSO2 API Cloud.

10. Log in to WSO2 Cloud by going to http://cloud.wso2.com, clicking the Sign In link and then selecting WSO2
API Cloud.

11. You need to construct and then copy your username which would be <email_address>@<tenant_domain>.

12. Create a Base64-encoded string of your API Cloud's credentials, separated by a colon
as <username>:<password>.

Copyright © WSO2 Inc. 2014-2017 93


WSO2 API Cloud

13. Execute the following command to import the API to the API Cloud:

curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>" -F
file=@"<full_path_of_zip_file>" -k -X POST
"https://api.cloud.wso2.com/api-import-export-2.1.0-v2/import-api?pre
serveProvider=false"

For example:
curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>" -F
file=@"/Users/Admin15/Downloads/myExportedAPI.zip" -k -X POST
"https://api.cloud.wso2.com/api-import-export-2.1.0-v2/import-api?pre
serveProvider=false"

Tip: Make sure the name and context of the API that you are importing (e.g., PhoneTest and
/phonetest) do not duplicate that of an existing API in the API Cloud.

14. Sign in to WSO2 API Cloud and note that the API that you imported now appears in the API Publisher.

Copyright © WSO2 Inc. 2014-2017 94


WSO2 API Cloud

15. Note that the API in the Cloud is in the CREATED state although it was in the PUBLISHED state in your local
API Manager instance. This is done to enable you to modify the API before publishing it.

In this tutorial, you created an API in an API Manager and exported that to WSO2 API Cloud without having to
recreate the API from scratch.

Migrating your API from WSO2 API Cloud to a APIM Local Setup

Any user with admin privileges can migrate the APIs from WSO2 API Cloud to another environment without having
to recreate the APIs.

In this tutorial, you create a API in WSO2 API cloud, migrate an API from WSO2 API Cloud, set up an
instance of WSO2 API Manager (WSO2 APIM) in your local environment, and then migrate that API from
WSO2 API Cloud to the local setup.

Copyright © WSO2 Inc. 2014-2017 95


WSO2 API Cloud

Let's get started!

1. Log in to WSO2 Cloud by going to https://cloud.wso2.com, clicking the Sign In link, selecting WSO2 API
Cloud, and entering your credentials.
2. Create and publish an API with the following details. If you do not know how to create and publish an API,
see Create and Publish an API.

Tab Parameters Values


Name

Design Name PhoneTest


Tab

Context /phonetest

Version 1.0.0

Visibility Public

API Click Next without entering anything and the system will prompt you to add a
Definition wildcard resource (/*). Click Yes.

Implement Production http://ws.cdyne.com/phoneverify/phoneverify.asmx


Tab -> Endpoint
Managed
API

Manage Tier Gold


Tab Availability
You cannot import a tier to an environment if it is not supported there,
although it is supported in the source environment.
For example, if you may have a tier (e.g., Gold-Updated tier) that is
supported in WSO2 API Cloud, but not in your local WSO2 API
Manager setup. Therefore, in the latter mentioned scenario you cannot
import the tier from WSO2 API Cloud to your local machine.

3. You need to construct and then copy your username which would be <email_address>@<tenant_domain>.
4. Use command line (if you are on mac/linux environment) or an online Base64 encoder such as https://www.
base64encode.org/, to create a Base64-encoded string of your WSO2 API Cloud's credentials, using the
following format.
<username>:<password>

If you are on mac/linux environment you can use following command.


echo -n <username>:<password> | base64

Example: echo -n admin:admin | base64

Copyright © WSO2 Inc. 2014-2017 96


WSO2 API Cloud

5. Install cURL in your local machine if it is not already installed.

6. Execute the following command to export your API from your tenant account in the WSO2 API Cloud as a
ZIP file.

curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>"
-X GET
"https://api.cloud.wso2.com/api-import-export-2.1.0-v2/export-api?nam
e=<API_Name>&version=<API-Version>
&provider=<API_provider>" -k > <ZIP_File_Name>.zip

According to our example, the command is:


curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>=" -X GET
"https://api.cloud.wso2.com/api-import-export-2.1.0-v2/export-api?nam
e=PhoneTest&version=1.0.0&provider=admin" -k > myExportedAPI.zip

You have exported an API to a ZIP file. Let's import that to your local WSO2 API Manager environment.

7. Setup an instance of WSO2 API Manager in your local environment.

1. Go to http://wso2.com/products/api-manager/ and download WSO2 API Manager 2.0.0 by clicking the


DOWNLOAD button in the upper right-hand corner.

To migrate APIs, your local environment must have the same API Manager version that the
API Cloud runs on.

2. Extract the ZIP file to a suitable location in your machine. Let's call this location <APIM_HOME>.
3. To export the API that you will later create in the WSO2 API Cloud, you need the API Import/Export
tool provided by WSO2. Download this WAR file and copy it to the <APIM_HOME>/repository/dep

Copyright © WSO2 Inc. 2014-2017 97


3. WSO2 API Cloud

loyment/server/webapps folder. It deploys the API Import/Export tool in your API Manager
server.
4. Start the WSO2 API Manager by executing one of the following commands:
On Windows: <APIM_HOME>\bin\wso2server.bat --run
On Linux/Solaris/Mac OS: sh <APIM_HOME>/bin/wso2server.sh

8. Using an online Base64 encoder such as https://www.base64encode.org/, create a Base64-encoded string of


your credentials of the WSO2 API Manager in the following format.
<username>:<password>
In this example, it is admin:admin.

Only users with admin privileges can migrate APIs between environments using the API
Import/Export tool.

9. Navigate to a suitable location using the command-line or terminal and execute the following cURL command
to import your API to your WSO2 API Manager local environment.

curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>" -F
file=@"<full_path_of_zip_file>" -k -X POST
"https://<APIM_HOST:Port>/api-import-export-2.1.0-v2/import-api?prese
rveProvider=false"

For example:
curl -H "Authorization:Basic
<base64-encoded-credentials-from_previous_step>" -F
file=@"/Users/Admin15/Downloads/myExportedAPI.zip" -k -X POST
"https://localhost:9443/api-import-export-2.1.0-v2/import-api?preserv
eProvider=false"

Copyright © WSO2 Inc. 2014-2017 98


WSO2 API Cloud

Tip: Make sure the name and context of the API that you are importing (e.g., PhoneTest and /phone
test) do not duplicate that of an existing API in the local WSO2 API Manager environment.

10. Log in to your local setup of WSO2 API manager and note that the API that you imported now appears in the
API Publisher.

Note that the API in the local API Manager instance is in the CREATED state although it was in the
PUBLISHED state in the WSO2 API Cloud. This is done to enable you to modify the API before
publishing it.

In this tutorial, you created an API via WSO2 API Cloud and exported that to your WSO2 API Manager environment
without having to recreate the API from scratch.

Publish and Invoke a SOAP API

WSO2 API Cloud supports the management of both REST and SOAP APIs. In this tutorial, we create and publish an
API with a SOAP endpoint and then invoke it using integrated and external tools.

In this tutorial, you create and publish an API with a SOAP backend and then invoke it using the
integrated API Console and a third-party tool (SOAP UI).

See the following topics for a description of the concepts that you need to know when invoking an API:

Applications
Throttling
Access tokens

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. Log in to the API Publisher and click ADD NEW API.


2. Select the option to design an API with an existing SOAP endpoint, give the endpoint URL and click Start
Creating.

Copyright © WSO2 Inc. 2014-2017 99


WSO2 API Cloud

We use the WSDL http://ws.cdyne.com/phoneverify/phoneverify.asmx?wsdl from CDYNE as the endpoint


here, but you can use any SOAP backend of your choice.

3. The Design tab of the API opens. Give the information in the table below and click Implement to proceed to
the implementation phase.

Field Sample value

Name SoapTest

Context /soaptest

Version 1.0

Copyright © WSO2 Inc. 2014-2017 100


WSO2 API Cloud

4. Click the Managed API option.


5. Provide the production endpoint, which is http://ws.cdyne.com/phoneverify/phoneverify.asmx in this example,
and click Manage.

Copyright © WSO2 Inc. 2014-2017 101


WSO2 API Cloud

6. In the Manage tab, select the Gold tier, scroll down and click Save and Publish.

Copyright © WSO2 Inc. 2014-2017 102


WSO2 API Cloud

You have now published the SOAP API to the API Store. Let's subscribe to it.
7. When prompted, choose to open the newly published API in the API Store.
8. The SoapTest API opens. Select an application (e.g., DefaultApplication), the Gold tier and subscribe to the
API.

9. Click the APPLICATIONS menu and click the Production Keys tab. If you have an access token already
generated, scroll down and click Re-generate. By default, access tokens expire an hour after creation, unless
you change the expiration time.

Copyright © WSO2 Inc. 2014-2017 103


WSO2 API Cloud

You have now subscribed to an API in the API Store. Let's invoke it using the SOAP UI.
10. Download the SOAP UI installation that suits your operating system from http://www.soapui.org/ and open its
console.
11. In the SOAP UI, right click on the Projects menu and create a new SOAP project.

12. Give your API's WSDL and click OK. In this case, the WSDL is http://ws.cdyne.com/phoneverify/phoneverify.
asmx?wsdl.

Copyright © WSO2 Inc. 2014-2017 104


12. WSO2 API Cloud

13. The WSDL defines two operations. Let's work with CheckPhoneNumber. Double click Request 1. As this
API is protected by OAuth, add an authorization header to your request by clicking the add sign on the Heade
r t a b o f t h e c o n s o l e .

14. Add the following values and submit the request:

1. Give the value of the Authorization header that you added in the previous step as 'Bearer <the access
token in step 9>.

2. Change the endpoint in the SOAP UI to the production URL of the API. You can copy the production
URL from the API's Overview tab.

3. Give any value (say 18006785432) as the PhoneNumber and 0 as the LicenseKey.

Copyright © WSO2 Inc. 2014-2017 105


WSO2 API Cloud

15. N o t e that the response appears in the SOAP UI.

You have invoked the API using a SOAP client. Let's invoke the same API using the integrated Swagger
console in the API Cloud.

16. Back in the API Store, click the API to open it and go to its API Console tab.

Copyright © WSO2 Inc. 2014-2017 106


WSO2 API Cloud

17. Expand the POST method, enter the following, and invoke the API.

SOAP Request
<soapenv:Envelope
xmlns:soapenv="http://schem
as.xmlsoap.org/soap/envelop
e/"
xmlns:quer="http://ws.cdyne
.com/PhoneVerify/query">
<soapenv:Header/>
<soapenv:Body>

<quer:CheckPhoneNumber>
<!--Optional:-->

<quer:PhoneNumber>180067854
32</quer:PhoneNumber>
<!--Optional:-->

<quer:LicenseKey>0</quer:Li
censeKey>

</quer:CheckPhoneNumber>
</soapenv:Body>
</soapenv:Envelope>

SOAP Action http://ws.cdyne.com/PhoneVerify/query/CheckPhon


eNumber

Copyright © WSO2 Inc. 2014-2017 107


WSO2 API Cloud

18. Note the API response that appears on the console.

Copyright © WSO2 Inc. 2014-2017 108


WSO2 API Cloud

In this tutorial, you have created an API with a SOAP backend and invoked it using both the integrated Swagger API
Console in the API Cloud as well as an external tool.

Backend Integration
How do I...

Pass a Custom Authorization Token to the Backend


Connect to your Backend Services from WSO2 API Cloud

Pass a Custom Authorization Token to the Backend

This tutorial uses the WSO2 API Manager Tooling Plug-in.

When you send an API request to the backend, you pass a token in the Authorization header of the request. The
API Gateway uses this token to authorize access, and then drops it from the outgoing message. In this tutorial, we
explain how to pass a custom authorization token that is different to the authorization token generated by the API
Cloud to the backend.

Copyright © WSO2 Inc. 2014-2017 109


WSO2 API Cloud

In this tutorial, you have a sample JAX-RS backend deployed in the Cloud and it always expects 1234
as the authorization token. In your API request, you pass the token that is generated by the API Cloud in
the Authorization header, and 1234 in a Custom header. The mediation extension you write extracts
the value of the Custom header, and sets it as the Authorization header before sending it to the
backend.

Here's a summary:

Client (headers: Authorization, custom) -> Gateway (drop: Authorization,


convert: custom->Authorization) -> Backend

See the following topics for the other methods of securing your backend services with the API Gateway:

Public backend service security


Private backend service security

Let's get started.

1. Download and install the WSO2 API Manager Tooling Plug-in if you have not done so already. Open Eclipse
by double clicking the Eclipse.app file inside the downloaded folder.

2. Click Window > Open Perspective > Other to open the Eclipse perspective selection window. Alternatively,
click the Open Perspective icon shown below at the top right corner.

3. On the dialog box that appears, click WSO2 APIManager and click OK.

Copyright © WSO2 Inc. 2014-2017 110


WSO2 API Cloud

4. On the APIM perspective, click the Login icon as shown below.

5. On the dialog box that appears, enter the cloud URL, username (in the format <email@company_name>), a
nd password of the Publisher server.

6. On the tree view that appears, expand the folder structure of the existing API.

7.

Copyright © WSO2 Inc. 2014-2017 111


WSO2 API Cloud

7. Right-click on the in sequence folder and click Create to create a new in sequence.

8. Name the sequence TokenExchange.

9. Your sequence now appears on the APIM perspective. From under the Mediators section, drag and drop a P
roperty mediator to your sequence and give the following values to the mediator.

Tip: The Property Mediator has no direct impact on a message, but rather on the message context
flowing through Synapse. For more information, see Property Mediator in the WSO2 ESB
documentation.

Property Name New Property

New Property Name Custom

Value Type EXPRESSION

Value Expression get-property('transport', 'Custom')

Copyright © WSO2 Inc. 2014-2017 112


WSO2 API Cloud

10. Similarly, add another Property mediator to your sequence and give the following values to the mediator.

Property Name New Property

New Property Name Authorization

Value Type EXPRESSION

Value Expression get-property('Custom')

Property Scope transport

Copyright © WSO2 Inc. 2014-2017 113


WSO2 API Cloud

11. Add a third Property mediator to your sequence and give the following values to the mediator.

Property Name New Property

New Property Name Custom

Property Action remove

Property Scope transport

Copyright © WSO2 Inc. 2014-2017 114


WSO2 API Cloud

12. Save the sequence.

13. Right-click on the sequence and click Commit File to push the changes to the Publisher server.

Copyright © WSO2 Inc. 2014-2017 115


WSO2 API Cloud

Let's create a new API and engage the sequence you created to it.

14. Log in to the API Publisher, click the Add link, and give the information in the table below.

Field Sample value

Name TestAPI1

Context /test1

Version 1.0.0

Visibility Public

Copyright © WSO2 Inc. 2014-2017 116


WSO2 API Cloud

15. Leave the Resources section blank, and click Implement. When prompted, add a wildcard resource (/*).
Click Yes and then click Implement again to move to the Implement tab.

16. In the Implement tab, give the information in the table below.

Field Sample value

Endpoint HTTP endpoint


type

Production http://wso2cloud-custom-auth-header-sample-1-0-0.wso2apps.com/custom-auth-heade
endpoint

17. Select the Enable Message Mediation check box, engage the In sequence that you created earlier, and
click Manage.

Copyright © WSO2 Inc. 2014-2017 117


WSO2 API Cloud

18. I n the Manage tab, select the Gold tier.

19. Click Save and Publish to publish the API to the API Store.
Let's subscribe to the API and invoke it.

20. Go to the API Store by clicking the Go to API Store link at the top right-hand corner of the screen. If you are
not logged in already, use the same credentials that you used to log in to the API Cloud.

21. Click TestAPI1, and subscribe to the API using an available application and the Gold tier. If there are no
applications available by default, create one.

Copyright © WSO2 Inc. 2014-2017 118


WSO2 API Cloud

22. Click the APPLICATIONS menu, and click the application that you used to subscribe to the API with ( Defaul
tApplication, in this example). Go to its Production Keys tab, and re-generate its access token. By
default, access tokens expire an hour after application creation.

23. Install any REST client on your machine. We use cURL here.

24. Go to the command-line, and invoke the API using the following cURL command. In this command, you pass
the token that the backend expects, i.e., 1234, in the Custom header with the authorization token that the
system generates in the Authorization header.

curl -H "Authorization: Bearer <access token>" -H "Custom: Bearer


1234" <API URL>

Copyright © WSO2 Inc. 2014-2017 119


WSO2 API Cloud

Note the following:

<access token> is the token that you got in step 20.


<API URL> appears on the API's Overview page in the API Store. Copy the HTTP endpoint. If you
select the HTTPs endpoint, be sure to run the cURL command with the -k option.

Here's an example:

curl -H "Authorization: Bearer DNp94L7mAT0e3Oj0QuUxOrmSIt0a" -H


"Custom: Bearer 1234"
'http://gateway.api.cloud.wso2.com:8280/t/companyn1/test1/1.0.0'

25. Note the response that you get in the command line. According to the sample backend used in this tutorial,
you get the below response.

{"code":200,"message":"Authorization header validation successful"}

In this tutorial, you passed a custom token that the backend expects along with the system-generated Authorization
token, and invoked an API successfully by swapping the system's token with your custom token.

Connect to your Backend Services from WSO2 API Cloud

According to the architecture of WSO2 API Cloud, all API calls that go out to your backend services from WSO2 API
Cloud go through the Cloud's API Gateway. The API Gateway handles user requests, user authentication via OAuth,
enforces security policies etc.

In order to connect to your backend services from the API Cloud, the API Gateway should connect to your backend
services.

If your backend services are exposed to the Internet (e.g., hosted in WSO2 App Cloud or another cloud platform),
then the API Gateway can connect to them via their Internet URLs. If your backend services are private to your
Intranet, WSO2 supports the following methods to set up the connectivity from the API Gateway to your backend
services.

Using a reverse proxy in your DMZ. The API Gateway then connects to the publicly visible reverse proxy,
which in turn passes the calls to the backend service.
Using a VPN link between the API Cloud and your Intranet.

See Expose your On-Premises Backend Services to the API Cloud for details.

If you choose to grant access to your private backend services through a reverse proxy or a VPN, it is highly
recommended to Secure your Backend Services as your private backend services will be exposed to a
multi-tenanted Cloud environment.

Expose your On-Premises Backend Services to the API Cloud

All API calls that go out to your backend services from WSO2 API Cloud go through the Cloud's API Gateway.
The API Gateway handles user requests, user authentication via OAuth, enforces security policies etc.

When your backend services are private to your Intranet, the API Gateway cannot access them over the Internet.

Copyright © WSO2 Inc. 2014-2017 120


WSO2 API Cloud

Therefore, you must expose your internal services to the public so that they can be accessed by the API Gateway.

In this tutorial, you learn the different ways in which you can allow WSO2 API Cloud to access the
private backend services in your network.

Let's get started!

Expose your services using a DMZ server


Expose your services using a VPN

Expose your services using a DMZ server

You can place a reverse proxy in your demilitarized zone (DMZ), and connect your backend services to it. All the
calls to the backend services will then be routed by the reverse proxy. The steps below explain how you can do this
using a sample backend service and NGINX as the reverse proxy.

Before you begin,

Secure your backend services as they will be publicly accessible after you expose them via the
reverse proxy.

Set up NGINX in the DMZ of your Intranet. See NGINX installation instructions and basic commands.

Tip: Although the screenshots given here may vary depending on your API and the backend service
implementation, you can follow the same instructions. Also, we use NGINX as the reverse proxy here but yo
u can use any other technology in a similar way.

1. Go to the <NGINX_HOME>/sites-enabled folder and create a VHost file. It routes the requests that come
to NGINX with the required hostname to your internal backend service.

2. Add the following in the config file that you created in step 1:

Create an upstream and point it to the IP and port of the actual backend service.

Inside the server{} block, give the name of the server and the port that the requests are coming in
from. In this case, it is mycompany.services.com.

Inside the location{} block, route a request to the actual backend service if the request comes in
the pattern of the server_name mentioned above.

Copyright © WSO2 Inc. 2014-2017 121


WSO2 API Cloud

upstream myservice {
server <IP_of the backend_service>:<port_of the backend_service>;
#For example, server 10.5.10.70:9443;
}
server {
listen 80;
server_name mycompany.services.com;
location / {
include /etc/nginx/proxy_params;
proxy_pass https://myservice/;
}
access_log /mnt/var/log/nginx/mycompnay/access.log;
error_log /mnt/var/log/nginx/mycompany/error.log debug;
}

3. Save and reload your NGINX configuration using the following command:

service nginx reload

Next, let's make sure that the host that we mentioned in the above VHost config (i.e.,
mycompany.services.com) publicly resolves to the IP address of the reverse proxy server. If not, when you
call this endpoint from WSO2 API Cloud, it will not be able to identify the location correctly.

4. In an available DNS server, map the IP of your NGINX with the domain name that you specified as the
server_name (i.e., mycompany.services.com).

10.5.10.49 -> mycompany.services.com


// 10.5.10.49 is the IP addresses of the server where placed your
reverse proxy

Once you have done the required configs in the NGINX reverse proxy, test whether a call is correctly routed
through the NGINX to your backend services.

5. Send the following Curl request using the command-line or the Terminal.
In this example, the backend is secured using basic auth. Therefore, we pass the <base64-encoded
username:password> in the Authorization header.

curl -k -X GET --header "Authorization: Basic <base64-encoded


username:password>"
http://mycompany.services.com/jaxrs_basic/services/customers/customer
service/customers/123

6. Check whether you get a result from your actual backend service. If so, your reverse proxy configuration has
been done correctly.

Now that the configurations are complete, let's design the API using the API Cloud.

7.

Copyright © WSO2 Inc. 2014-2017 122


WSO2 API Cloud

7. Log in to WSO2 API Cloud and start to create a new API by clicking the ADD NEW API link. Alternatively,
you can edit an existing API.

8. In the Design tab of the API, under the API Definition, give the URI template that matches the resources of
y o u r b a c k e n d s e r v i c e .
In this example, the backend requires you to pass a customerId. So, the URL pattern is jaxrs_basic/serv
ices/customerservice/customers/{customerId}.

9. In the Implement tab, specify the endpoint that will be resolved at your reverse proxy before calling your
backend service. According to the reverse proxy configuration in this example, the endpoint is http://mycompa
ny.services.com/.

10. Since the backend service is secured using basic authentication in this example, set the Endpoint
Security Scheme to Secured, the Endpoint Auth Type to Basic Auth and give the credentials expected
b y t h e b a c k e n d s e r v i c e .

Copyright © WSO2 Inc. 2014-2017 123


WSO2 API Cloud

11. In the Manage tab, select all the available tiers and save and publish your API.

12. Go to the API Store, subscribe to the API and click its API Console tab using which you can invoke the API.

13. Give a customerId (say 123), invoke the API and note the response that is displayed. The API Gateway
makes a call to your reverse proxy, which is resolved using the DNS mapping. The reverse proxy then calls
your backend service and returns the response to the API Console.

Copyright © WSO2 Inc. 2014-2017 124


WSO2 API Cloud

With the help of a DMZ server, you have invoked a backend service that is private to your Intranet using an API in
WSO2 API Cloud.

Expose your services using a VPN

If you are unable to use a reverse proxy, you have the option to create a VPN connection between your network and
WSO2 API Cloud.

Tip: Make sure you Secure your backend services as they will be publicly accessible after you expose them
via the VPN.

This solution is fully secured and managed.

Each customer gets a separate subnetwork in the WSO2 Cloud space.


The subnetwork has a highly available load-balancer cluster, which connects to your network via AWS VPN.
To get started, click the Support menu in API Cloud interface and submit your request. WSO2 will respond
and guide you through the setup process.

Copyright © WSO2 Inc. 2014-2017 125


WSO2 API Cloud

Secure your Backend Services

WSO2 API Cloud allows you to turn your backend services into managed APIs through which subscribers can
consume your backend services. According to the architecture of WSO2 API Cloud, all API calls that go out to
your backend services go through the Cloud's API Gateway. The API Gateway handles user requests, user
authentication via OAuth, enforces security policies etc.

The API Gateway has the ability to intercept API requests and apply various security policies and mechanisms
to secure the connection between the API Gateway and your backend service. Upon validation of a policy, the
Gateway passes Web service calls to the actual backend.

In this tutorial, you learn the different ways in which you can secure the link between WSO2 API Cloud
and the backend services of the APIs in the API Cloud.

Let's get started.

Using basic authentication


Using digest authentication
Using a custom authorization token
Using Mutual SSL (certificate-based API Gateway)
Whitelisting IPs

Using basic authentication

One of the simplest ways to enforce access control to Web resources is using a username and password (i.e., basic
authentication).

1. Secure your backend services using a username and password.

Next, design your API in WSO2 API Cloud in a way that the API sends the authentication details with the
request that is going to the backend.

Copyright © WSO2 Inc. 2014-2017 126


WSO2 API Cloud

2. Log in to the API Publisher and click the Edit icon of the API that points to a public backend service you
s e c u r e d . F o r e x a m p l e :

3. Go to the Implement tab of the API, and click the Show More Options link. Then, set the Endpoint
Security Scheme to Secured, the Endpoint Auth Type to Basic Auth and give the credentials that you
used to secure your backend service.

Copyright © WSO2 Inc. 2014-2017 127


WSO2 API Cloud

You have now configured the API to send the basic auth credentials with a request that goes to the backend.

Using digest authentication

Digest authentication is similar to basic authentication, but is more secure, and prevents replay attacks. It applies
an MD5 cryptographic hash using nonce values (a one-time-use string) to the credentials before sending them to the
backend.

1. Secure your backend services using digest authentication .


Next, design your API in WSO2 API Cloud in a way that the API sends the authentication details with the
request that is going to the backend.

2. Log in to the API Publisher and click the Edit icon of the API that points to a public backend service you
s e c u r e d . F o r e x a m p l e :

Copyright © WSO2 Inc. 2014-2017 128


WSO2 API Cloud

3. Go to the Implement tab of the API, and click the Show More Options link. Then, set the Endpoint
Security Scheme to Secured, the Endpoint Auth Type to Digest Auth and give the credentials that you
used to secure your backend service.

Copyright © WSO2 Inc. 2014-2017 129


WSO2 API Cloud

You have now configured the API to send the digest auth credentials with a request that goes to the backend.

Using a custom authorization token

Rather than using credentials, you can pass a token (usually a string or a series of numbers) to the backend with the
API calls. This custom authorization token which should be recognized and validated by your backend in order to be
granted access. For a step-by-step tutorial, see Pass a Custom Authorization Token to the Backend.

Using Mutual SSL (certificate-based API Gateway)

In Mutual SSL, also known as certificate-based mutual authentication, trust between the API Cloud and your
backend services are established by verifying a provided certificate so that both parties are sure of each other's
identity. The diagram below depicts this scenario:

Copyright © WSO2 Inc. 2014-2017 130


WSO2 API Cloud

To set up, provide a trusted certificate to the WSO2 Cloud team as follows:

1. Log in to the API Cloud and click theSupport menu at the top.

2. Submit a request to the WSO2 Cloud team with your backend hostname.
3. You get a response email from WSO2. After that is received, send us the backend certificate with which you
want to configure mutual SSL (e.g., your_backend_cert.crt).
4. We add your certificate to WSO2 servers and send you our public certificate.
5. You add the public certificate to your backend servers.

Whitelisting IPs

You can secure your backend in such a way that it only accepts calls proxied by the API Cloud. Configure your
network to accept the IPs of trusted sources such as WSO2 API Cloud. This makes your backend services
accessible to API consumers who make the requests via the API Cloud.

To get started, click the Support menu in the API Cloud interface and submit your request. WSO2 will respond with
the IP range that you need to whitelist.

Developer Portal
How do I...

Use the Community Features


Customize the API Store Theme
Customize Cloud URLs

Use the Community Features

The API Store provides several community features to build and nurture an active community of users for your
APIs. This is required to advertize APIs, learn user requirements and market trends.

In this tutorial, you explore what community features that are available in the API Store.

Copyright © WSO2 Inc. 2014-2017 131


WSO2 API Cloud

See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial, which introduces the following features:

Use the search facility

You can search for APIs in the API Publisher or Store in the following ways:

Clause Syntax

By the API's As this is the default option, simply enter the API's name and search.
name

By API the provider:xxxx . For example, provider:admin


API provider
Provider is the user who created the API.

By the API version:xxxx . For example, version:1.0.0


version
A version is given to an API at the time it is created.

By the context context:xxxx. For example, context:/phoneverify

Context is the URL context of the API that is specified as /<context_name> at the time the API is
created.

By the API's status:xxxx . For example, status:PUBLISHED


status
A state is any stage of an API's lifecycle. The default lifecycle stages include created,
prototyped, published, deprecated, retired and blocked.

By description description:xxxx

A description can be given to an API at the time it is created or later. There can be APIs without
descriptions as this parameter is optional.

By the subcontext:xxxx . For example, subcontext:/checkphonenumber.


subcontext
A subcontext is the URL pattern of any resource of the API. API resources are created at the
time the API is created or later when it is modified. For example, if you create a resource by the
name checkphonenumber, then /checkphonenumber becomes one subcontext of the API.

By the content doc:xxxx


of the API
documentation You can create API documentation in-line (using the API Publisher UI itself), by uploading a file
or referring to an external URL. This search enables you to give a sentence or word phrase that
is inside the in-line documentation and find the API that the documentation is added for.

Rate and comment

Copyright © WSO2 Inc. 2014-2017 132


WSO2 API Cloud

Rates and comments give useful insights to potential API consumers on the quality and usefulness of an API. You
can rate and comment on APIs per each version.

1. Log in to the API Store and click on a published API.


2. The API's Overview page opens. Note the rating and commenting options there:

3. Add a rating and a comment. Note that the comments appear sorted by the time they were entered, alongside
the author's name.

Share on social media/e-mail

1. Log in to the API Store and click on a published API.


2. On the API's Overview page, you get the social media options using which you can share and advertize
APIs.

Copyright © WSO2 Inc. 2014-2017 133


WSO2 API Cloud

Embed an API widget

A widget is an embeddable version of the API in HTML that you can share on your Website or other Web pages.
This is similar to how Youtube videos can be embedded in a Web page.

1. Log in to the API Store and click on a published API.


2. Note the Embed tab under the API's sharing options.

Copyright © WSO2 Inc. 2014-2017 134


WSO2 API Cloud

Customize the API Store Theme

A theme consists of UI elements such as logos, images, landing page text, background colors etc. WSO2 API Store
comes with a default theme called Fancy. The easiest way to change the user interface of the API Store is by
customising the default theme.

In this tutorial, you change the default API Store theme by applying your customizations.

All themes have a folder structure similar to the following:

Copyright © WSO2 Inc. 2014-2017 135


WSO2 API Cloud

Because the default theme already has most of the UIs and JSON logic defined, in a typical scenario, you
do not implement a theme from scratch. You can customise the default theme by bundling up the changes
(e.g., CSS code, images) as a .zip file and uploading it through the Admin Dashboard Web application.
Once uploaded, the files in the .zip override the corresponding files in the default theme. The rest is
inherited from the default theme.

Tip: To override the default theme, you must only upload UI changes as CSS code, fonts as SVG, TTF,
EOT, WOFF , WOFF2 and OTF files, and images as JPG, PNG, and GIF file. JSON logic in the .zip file will
not be applied due to security reasons.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. Download the default theme from fancy.zip, unzip it and rename the folder according to the name of your new
theme (e.g., ancient). Let's call this folder the <THEME_HOME>.
2. To change the logo of the API Store, replace <THEME_HOME>/libs/theme-wso2_1.0/images/logo-in
verse.svg with the preferred logo.

3. To change the favicon of the API Store, replace <THEME_HOME>/images/favicon-store.png with the
preferred icon.
4. To change the logo of the API Store's Self Signup page, replace <THEME_HOME>/images/logo-white.pn
g with the preferred logo.
5. Open the <THEME_HOME>/css/custom.css file using a text editor and add the following CSS code to the
end of the file. Note the code comments to get an idea what each line of code does.

/* Change the color of the header */


header.header-default {
background: #555555 none repeat scroll 0 0;
}

/* Change the color of the Top Navigation Bar */


.navbar {
background: #555555 none repeat scroll 0 0;
}

/* Change the color of the search box and its fonts */


.search-wrap .appm-content-search {
background: #ffffff;

Copyright © WSO2 Inc. 2014-2017 136


WSO2 API Cloud

color: #000000;
}

.appm-content-search::-moz-placeholder {
color: #000000;
}

/* Change the color of the Search box dropdown button */


.search-wrap .btn.dropdown-toggle {
background: #555555 none repeat scroll 0 0;
border-color: #555555;
}

/* Change the color of the Search box search button */


.search-wrap .btn.wrap-input-right {
background: #555555;
}

/* Change the font of the menus, headings, labels etc. to Verdana. You
give several fonts here to ensure maximum compatibility, if in case
one font fails in a given browser/OS. Fonts will be applied in the
order you list them. */
body,textarea,pre,.navbar-search .search-query{
font-family: Verdana, Arial, Helvetica, monospace, san-serif;
}

label, input, button, select, textarea{


font-family: Verdana, Arial, Helvetica, monospace, san-serif;
}

h1,h2,h3,h4,h5{
font-family: Verdana, Arial, Helvetica, monospace, san-serif;
}

/* To change the background color of the body */


body{
background: #D0D0D0;
}

/* To change the color of the buttons. Note that changing only the
background color will not have a visual impact if you leave the
gradients as they are */
.btn-primary {

Copyright © WSO2 Inc. 2014-2017 137


WSO2 API Cloud

background-color: #800004;
background-image: linear-gradient(to bottom, #cc0022, #cc0044);
}

6. Since you plan to upload this as a sub-theme of the default main theme, delete all the files in your <THEME_H
OME> folder except the ones that you just edited. The rest of the files will be automatically applied from the
main theme.
7. Go inside the <THEME_HOME> folder, select all the files/folders inside it (Ctrl+A) and right click to archive
all the selected files and folders together. Then rename the archive files to ancient.zip.

Tip: Be sure to create the archive file by selecting all the files/folders (Ctrl+A) and right clicking on all
the selected artifacts.

8. Log in to WSO2 API Cloud by going to https://cloud.wso2.com, clicking the Sign In link and then selecting
WSO2 API Cloud.
9. Click the Admin Dashboard menu under the Configure menu to open the Admin Dashboard.

10. The Admin Dashboard opens. Click SETTINGS -> UPLOAD TENANT THEME and upload your zip file (e.g.,
ancient.zip).

11. Open the API Store and the Signup page and note that your UI customizations are applied.

Copyright © WSO2 Inc. 2014-2017 138


WSO2 API Cloud

Tip: It can take up to 15 minutes for a new theme to be applied to the API Store.

In this tutorial, you applied a few selected UI changes to the API Store.

Customize Cloud URLs

In WSO2 API Cloud, the default base URL for the API Store is https://api.cloud.wso2.com. Subscribers
invoke the APIs published in this store through the API Gateway component. Therefore, the default base URL of the
APIs is http(s)://gateway.api.cloud.wso2.com.

You can use customized URLs that are more representative of your company or personal branding instead of using
the default URLs.

The following sections describe how to customize URLs:

Copyright © WSO2 Inc. 2014-2017 139


WSO2 API Cloud

Select the API Gateway region


Create SSL certificates and DNS records
Customize the API Gateway URL
Customize the API Store URL

Select the API Gateway region

WSO2 API Cloud currently supports regional gateways in Canada, US East, US West, Brazil (São Paulo), EU
(Ireland), EU (Frankfurt), Singapore, Tokyo, Sydney, Seoul, Mumbai, and Beijing. The default region is US East.
You can choose your region from the available options. Region selection requires you to use a custom URL for your
gateway. To use multiple regions, contact WSO2 API Cloud support via a support request or chat.

Selecting a different region requires the Getting Traction or a higher subscription plan. If you have a trial
account or a Starter plan, please upgrade your account.

Let's get started.

1. Log in to the API Cloud as the tenant admin.


2. In the API Publisher, click Configure and select Custom URL from the drop-down menu.

3. Click Modify to change the existing Gateway domain.

4. C l i c k Modify to change the default gateway region.

Copyright © WSO2 Inc. 2014-2017 140


WSO2 API Cloud

4.

After you modify the gateway region, all requests are routed to the new regional gateway that you
select.

5. Select the preferred region from the drop-down list and click Save.

6. N o t e the new Domain Name updated in the UI.

You can create a custom domain name, SSL certificates, and DNS records for the selected region. For more
information, see Create SSL certificates and DNS records.

Make sure your custom URL is set according to the changed gateway. For more information, see Customize
API gateway URL.

Create SSL certificates and DNS records

Copyright © WSO2 Inc. 2014-2017 141


WSO2 API Cloud

This tutorial explains how you can generate DNS records and SSL certificates to configure a custom URL for WSO2
API Cloud.

1. Install an SSL key generation tool. OpenSSL is used in this tutorial.

2. Using the command-line, navigate to a location of your choice in the server and execute the following
command to generate a private SSL key by the name private.key.

openssl genrsa -out private.key 2048

Note that the key file is generated in your folder location.

3. In the command-line, execute the following command to generate a certificate signing request file for your
custom URL. Be sure to change the business address in this command to your own.

openssl req -new -key private.key -sha256 -nodes -out request.csr


-subj "/C=US/ST=California/L=Mountain
View/O=WSO2/OU=IT/CN=developers.mytesturl.info"

Note that the certificate signing request file is generated in your folder location.

4. Go to a certificate vendor of your choice and use the certificate signing request file to obtain a certificate for
your domain. Any certificate that is accepted by browsers work. We used https://www.comodo.com/ as the
certificate authority in this tutorial.

When you are done, you typically receive an email with the certificate for your domain along with the
certificate authority's root and intermediate certificates. Some certificate authorities provide the root and
intermediate files as a single chain file, while others provide multiple files.

5. If you received multiple root and intermediate files from your certificate authority, use the cat utility (available
in Unix and Unix-based operating systems) to concatenate them to a single chain file ( chain.crt). For
example,

cat COMODORSADomainValidationSecureServerCA.crt
COMODORSAAddTrustCA.crt AddTrustExternalCARoot.crt > chain.crt

Tip: Do the following to concatenate the certificate files if you are using Microsoft Windows:

Open all certificate files except your domain certificate in a text editor like the notepad.

Create a new blank text file.

Copy the contents of all files in the reverse order and paste them into the new text file. For
example, copy intermediate 3, intermediate 2, intermediate 1, and then the root certificate.

Save the newly created file (say chain.crt).

Note that the chain.crt file should have content in the following order:

Copyright © WSO2 Inc. 2014-2017 142


WSO2 API Cloud

-----BEGIN CERTIFICATE-----
(Your Intermediate certificate:
COMODORSADomainValidationSecureServerCA.crt)
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
(Your Intermediate certificate: COMODORSAAddTrustCA.crt)
-----END CERTIFICATE-----

-----BEGIN CERTIFICATE-----
(Your Root certificate: AddTrustExternalCARoot.crt)
-----END CERTIFICATE-----

6. Reserve a domain name with any domain registrar and create DNS CNAME records that map the domain to
your API Store and Gateway URLs.

Tip: Most domain registrars provide step-by-step instructions in their websites. For your convenience,
we have listed the general steps below.

Expand to see the listed steps


Sign in to the domain registrar’s site.
Navigate to your Domain Name Server (DNS) management page. The location and name of
this page vary by the host, but can generally be found under the 'Domain Management' or
'Advanced Settings' section.
Find the CNAME settings. Under the 'CNAME value or alias,' enter the subdomain that you'd
like to map each URL to. The subdomain of developers.mytesturl.info is developers.
Set the CNAME destination to the API Cloud's custom DNS endpoint, which is customdns.api.
cloud.wso2.com. When configuring custom url for API gateway, if you select a region different
than the default region ( US East ) remember to set the CNAME destination according to the
following table.

Region Pointing URL

US East customdns.api.cloud.wso2.com

US West customdns-usw.api.cloud.wso2.com

Singapore customdns-sg.api.cloud.wso2.com

Sydney customdns-syd.api.cloud.wso2.com

Canada customdns-can.api.cloud.wso2.com

Brazil customdns-brz.api.cloud.wso2.com

EU (Ireland) customdns-ire.api.cloud.wso2.com

Copyright © WSO2 Inc. 2014-2017 143


WSO2 API Cloud

EU (Frankfurt) customdns-frk.api.cloud.wso2.com

Tokyo customdns-tky.api.cloud.wso2.com

Seoul customdns-seo.api.cloud.wso2.com

Mumbai customdns-mum.api.cloud.wso2.com

Beijing customdns-bjg.api.cloud.wso2.com

You now have the SSL certificates and DNS records that you require to configure a custom URL for the API
Cloud.

Customize the API Gateway URL

You can have a customized Gateway URL that is more representative of your company or personal branding. Follow
the steps below to customize your API Gateway URL.

1. Log in to the API Cloud as the tenant admin.


2. In the API Publisher, click Configure and select Custom URL from the dropdown menu.

3. C l i c k Modify to change the existing domain.

Copyright © WSO2 Inc. 2014-2017 144


WSO2 API Cloud

For more information on how to change the default Gateway region, see Select the API Gateway region.

You will not be able to change your default regional gateway (US East) if you have not subscribed to
Getting Traction or a higher plan. However, you can configure a custom URL by adding a custom
domain name with the CNAME pointing to customdns.api.cloud.wso2.com

4. Enter the API Gateway custom URL. In this example, we use www.developers.mytesturl.info.

5. Click Verify to check whether a CNAME record exists for this URL.

6. If the CNAME verification is successful, you are prompted for the SSL certificates. Upload the files that you
created in and click Proceed.

The certificate files should satisfy the following requirements:

File Requirements

Copyright © WSO2 Inc. 2014-2017 145


WSO2 API Cloud

SSL The certificate you got in step 6. It must satisfy the following requirements:
certificate In X509 format

Not self signed

Not expired

Issued directly or by a wild card entry for a provided custom URL. For example,

In the direct method, if the CNAME is store.wso2.com, the issued SSL file must contain stor
e.wso2.com

In the wildcard method, if the CNAME is store.wso2.com, the issued SSL file should be *.w
so2.com

SSL Key The private key of the certificate that you got in step 2 of Create SSL certificates and DNS
File records. It must be encrypted in the RSA format.

Chain The public key of the certificate that you got in step 5 of Create SSL certificates and DNS
File records. If the public key is included in the SSL file, extract it to a chain file.

Note that you receive a notification saying "Custom URL mapping is successfully added" if the files are
successfully uploaded.

Tip: Wait approximately 10 minutes for the changes to take effect as adding the configurations and
restarting the load balancers can take some time.

Copyright © WSO2 Inc. 2014-2017 146


WSO2 API Cloud

If you have selected a region that requires additional configurations, you see the following message
followed by an email with instructions.

The Cloud team will contact you via email once the regional gateway is ready with the custom URL
you have added.

7. Once the configurations above are successful, you can visit the API Store, select an API and note the new
API URLs in its Overview page. This changes according the new API Gateway URL.

Customize the API Store URL

Subscribers enter the API Store URL into a browser to get to your API Store. Follow the steps below to customize
the URL of your API Store.

1. Log in to the API Cloud as the tenant admin.


2. In the API Publisher, click Configure and select Custom URL from the dropdown menu.

Copyright © WSO2 Inc. 2014-2017 147


WSO2 API Cloud

3. Click Modify and enter the API Store custom URL. In this example, we use www.developers.mytesturl
.info.

4. Click Verify to check whether a CNAME record exists for this URL.

5. If the CNAME verification is successful, you are prompted for the SSL certificates. Upload the files that you
created and click Proceed.

The certificate files must satisfy the following requirements:

File Requirements

SSL This is the certificate you got in step 6. It must satisfy the following requirements:
certificate In X509 format

Not self signed

Not expired

Issued directly or by a wild card entry for a provided custom URL. For example,

In the direct method, if the CNAME is store.wso2.com, the issued SSL file must contain stor
e.wso2.com

In the wildcard method, if the CNAME is store.wso2.com, the issued SSL file should be *.w
so2.com

Copyright © WSO2 Inc. 2014-2017 148


WSO2 API Cloud

SSL Key The private key of the certificate that you got in step 2 of Create SSL certificates and DNS
File records. It must be encrypted in the RSA format.

Chain The public key of the certificate that you got in step 7 of Create SSL certificates and DNS
File records. If the public key is included in the SSL file, extract it to a chain file.

Note that you receive a notification saying "Custom URL mapping is successfully added" if the files are
uploaded successfully.

Tip: Wait approximately 10 minutes for the changes to take effect. Adding the configurations and
restarting the load balancers can take some time.

You have successfully changed the API Store domain name to a custom value.

6. Access the API Store using your new URL. In this example, the new API Store URL is https://www.devel
opers.mytesturl.info.

Copyright © WSO2 Inc. 2014-2017 149


WSO2 API Cloud

Copyright © WSO2 Inc. 2014-2017 150


WSO2 API Cloud

Policies and Monetization


How do I...

Enforce Throttling and Resource Access Policies


Enable Monetization

Enforce Throttling and Resource Access Policies

Throttling allows you to limit the number of hits to an API during a given period of time, typically to protect your
APIs from security attacks and your backend services from overuse, regulate traffic according to infrastructure
limitations and to regulate usage for monetization. For information on different levels of throttling in WSO2 Cloud,
see Throttling tiers.

In this tutorial, you engage throttling and resource access policies at various levels to your API and
observe how the API Gateway enforces them in the API.

Before you begin,

Follow Create and Publish an API to create and publish the PhoneVerification API.
Follow Invoke an API using cURL to subscribe to the API using the Bronze throttling tier.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. Log in to the API Store and select the PhoneVerification API.

2. Subscribe to the API using the Bronze tier if you haven't done so already.

3. In the API Store, click the APPLICATIONS menu, click DefaultApplication to open it, and then click the
Production Keys tab. If you already have an access token for the application, you may have to scroll down
and click Re-generate. Access tokens expire 1 hour after creation unless you extend the period.

Copyright © WSO2 Inc. 2014-2017 151


WSO2 API Cloud

Copyright © WSO2 Inc. 2014-2017 152


WSO2 API Cloud

Let's invoke this API.

4. Click on the API, then go to its API Console tab and expand the GET method.

5. Give values to the parameters (PhoneNumber 18006785432 and LicenseKey 0) and click Try it out to invoke
t h e A P I .

6.

Copyright © WSO2 Inc. 2014-2017 153


WSO2 API Cloud

6. Note the response that appears in the API Console. As we used a valid phone number in this example, the
response returns as valid.

7. Within a minute after the first API invocation, make another attempt to invoke the API.

8. Note that you get a throttling error saying that you exceeded your quota. This is because you subscribed to
the API on the Bronze throttling tier and the Bronze tier only allows you to make one call to the API per
minute.

Let's try to invoke the API using an unavailable resource name.


9. Click the APIs menu in the API Store, click the API you want to invoke and then copy the production URL in
the API's Overview tab.

Copyright © WSO2 Inc. 2014-2017 154


WSO2 API Cloud

10. Append the payload to the API's URL you copied earlier. For example, https://gateway.api.cloud.wso2.com:4
43/t/companyn3/phoneverify/1.0.0/CheckPhoneNumber?PhoneNumber=18006785432&LicenseKey=0.
Let's invoke the API.

11. Install cURL or any other REST client.

12. Go to the command-line and invoke the API using the following cURL command.
Note that the PhoneVerification API's resource name is CheckPhoneNumber, but we use an undefined
resource name as CheckPhoneNum.

curl -k -H "Authorization: Bearer <access token in step 3>" '<API's


URL in step 9>/CheckPhoneNum?PhoneNumber=18006785432&LicenseKey=0'

Here's an example:

curl -k -H "Authorization: Bearer 0bc0500523dddc5c973971f16b19103e"


'https://gateway.api.cloud.wso2.com:443/t/companyn3/phoneverify/1.0.0
/CheckPhoneNum?PhoneNumber=18006785432&LicenseKey=0'

13. Note that the call gets blocked by the API Gateway with a 'no matching resource' message. It doesn't reach
your backend services as you are trying to access a REST resource that is not defined for the API.

Copyright © WSO2 Inc. 2014-2017 155


WSO2 API Cloud

You have seen how the API Gateway enforces throttling and resource access policies for APIs.

Enable Monetization

Monetization allows API publishers to bill API subscribers for the consumption of the APIs available on their API
store (developer portal). This feature allows the API publisher to customize the patterns of monetization and also to
apply a pricing plan to the APIs in order to monetize them (the "Getting Traction" plan or above is required before
you can enable monetization).

Let's get started.

1. Log in to the API Cloud.


2. In the API Publisher, click the Monetization menu inside the trial menu.

3. If your account does not already have the "Getting Traction" pricing plan or above (for information on the
pricing plans, see http://wso2.com/cloud/pricing/), you will be prompted to upgrade your existing account or
create a new account–click OK and follow the instructions on the screen. If your account already has the
"Getting Traction" plan or above, skip to step 4.

Do the following to upgrade your account.

1. You will be prompted to select a plan to upgrade your account. Select a plan you prefer and click on
the corresponding button.

Copyright © WSO2 Inc. 2014-2017 156


WSO2 API Cloud
1.

2. Follow the instructions and add your credit card details to upgrade your account.

3. After upgrading your account to the "Getting Traction" plan or above, click the settings icon in the
upper right-hand corner of the screen, and then click the Monetization menu to return to the API

Copyright © WSO2 Inc. 2014-2017 157


WSO2 API Cloud
3.

Publisher.

4. You must create an account with Stripe to enable the WSO2 Cloud API Monetization feature. Stripe is an
American technology company, operating in over 25 countries, that allows both private individuals and
businesses to accept payments over the Internet. Click on Connect with Stripe to create a Stripe account.

You are redirected to the Stripe application page. You can either create a new account or use an existing
account.
To create your account, enter your account details in the Stripe application form and click Authorize
access to this account to activate your account.

Copyright © WSO2 Inc. 2014-2017 158


WSO2 API Cloud

Copyright © WSO2 Inc. 2014-2017 159


WSO2 API Cloud

Alternatively, you may already have a Stripe account.


1. If you already have an account with Stripe, click the Sign In button at the top right of your
screen.

2. Enter your credentials and log in.

Copyright © WSO2 Inc. 2014-2017 160


WSO2 API Cloud

5. Once you complete registration you will be able to return to the WSO2 Cloud API page and enable
monetization. Enter the password you use for your Cloud account, and then click the Enable Monetization b

Copyright © WSO2 Inc. 2014-2017 161


WSO2 API Cloud

utton.

6. A confirmation message appears to let you know that the configurations needed to power the monetization
feature have been added for your organization. Click OK.

7. The Subscription Tiers screen on the Admin Dashboard appears. The default tiers are Gold, Silver, and
Bronze. To start billing subscribers for usage of your APIs, and also to specify the rate plans that you want to
include for your API invocations, you must customize your existing subscription tiers, or define new
subscription tiers as Commercial (billable) instead of free.

Tip: If you have taken a different path from these steps, you can get to this screen by choosing Confi
gure -> Admin Dashboard from the top menu bar and clicking Subscription Tiers in the left
navigation pane.

Copyright © WSO2 Inc. 2014-2017 162


WSO2 API Cloud

8. Do one of the following:


To create a new commercial tier, click Add New Tier, specify the required values (be sure to select Co
mmercial for the billing plan), and click Save.
To edit an existing tier to become commercial, click the Edit link for that tier, set the billing plan to Com
mercial, and click Save.

In the example below, we are creating a new commercial tier named Platinum.

Copyright © WSO2 Inc. 2014-2017 163


WSO2 API Cloud

9. Click Monetization on the top menu bar.

Copyright © WSO2 Inc. 2014-2017 164


WSO2 API Cloud

10. On the Monetization Dashboard, display the left menu by clicking in the upper left corner, and then
click the Plans menu option. Alternatively, click the View icon in the Plans area.

11. The Plans screen appears, where you will now add payment plans for your commercial tiers. Click the Edit ic
on for the Platinum tier.

Tip: If you created a new tier and it is not yet displayed on this screen, it is still being added to the
registry, which can take up to 15 minutes.

12. Enter the required values for this commercial tier as shown below, and then click Save.

Copyright © WSO2 Inc. 2014-2017 165


12. WSO2 API Cloud

13. Notice that the payment plan for your commercial tier (Platinum) has been added successfully.

You are now ready to apply the payment plans to your APIs. (You can do this when creating or editing an
API.)

14. In the API Publisher, browse to the PhoneVerification API and click the Edit link next to its name.

Copyright © WSO2 Inc. 2014-2017 166


WSO2 API Cloud
14.

15. Navigate to the Manage tab, select the Platinum tier from the Subscription Tiers list, and click Save &
Publish.

Copyright © WSO2 Inc. 2014-2017 167


WSO2 API Cloud

16. Go to the API Store and notice that a label (tag) is added to each API as follows:
FREE: API has only free tiers
PAID: API has only commercial tiers
FREEMIUM: API has both commercial and free tiers

Copyright © WSO2 Inc. 2014-2017 168


WSO2 API Cloud

17. Click the PhoneVerification API to open it, select the default application and the Platinum tier, and click Subs
cribe.

18. Because you are subscribing to an API through a commercial tier, you are directed to a billing information
p a g e .

Copyright © WSO2 Inc. 2014-2017 169


WSO2 API Cloud

Tip: After subscribing to the API, you will get an email with your invoice. The invoice is in a
pre-defined template with the WSO2 logo and WSO2 as the service provider. Contact the WSO2
Cloud team to customize this template with your company's logo, name, and other details.

In this tutorial, you have applied a pricing plan to your WSO2 Cloud account, created a commercial tier, applied the
tier to an API, and seen how subscribers enter billing information in order to invoke the API through a commercial
tier.

User Management
How do I...

Register and Invite Members


Block Subscription to an API
Enable Self Signup to the API Store
Authenticate Users that are External to WSO2 Cloud
Customize Invitation Emails

Register and Invite Members

WSO2 offers different public, private and hybrid cloud solutions and all of them are collectively known as WSO2
Cloud (http://cloud.wso2.com). You can register to all of the public cloud offerings (e.g., the API Cloud, App Cloud)
using a valid e-mail address. For a description of the Cloud's user model, see Cloud's user model.

In this tutorial, you register your organization in the API Cloud and invite members to it.

Members are added to the Cloud in 2 steps:

Copyright © WSO2 Inc. 2014-2017 170


WSO2 API Cloud

Let's get started.

1. Go to http://cloud.wso2.com and sign up to any one of the public clouds. The UI guides you through the
signup process.
2. Log in to the organization that you created. You have admin rights to it.
3. Click the settings icon in the top right-hand corner of the screen and then click the Members menu.

Tip: You can create multiple different organizations under the same login using the Manage menu,
which is next to the Members menu.

4. C l i c k I n v i t e M e m b e r s .

5. Give valid e-mail addresses of the members, specify one or more roles to each member and invite.

Copyright © WSO2 Inc. 2014-2017 171


5. WSO2 API Cloud

You can customize the invitation emails by applying your own logo and changing the content. For
information on how to do this, see Customize invitation emails.

The API Cloud's user roles are given below:

Role Name Permissions

Publisher Log in to the API Publisher and Store


Manage the technical aspects of the API (coding, interfaces, documentation)
V e r s i o n A P I s
P u b l i s h A P I s
Manage the API lifecycle
View analytics

Subscriber Log in to the API Store


Search and view APIs and read API documentation
Subscribe to APIs
Use API user community features (rating, commenting, taking part in forums etc.)

Tip: You can assign different roles to the same member in different types of the cloud. For example,
you can assign user1@wso2.com the Developer and QA roles in the App Cloud and the Publisher
role in the API Cloud.

6. Note that the member is sent an invitation e-mail, which has to be accepted by him/her in order to be added
to the Cloud as a registered member.

Copyright © WSO2 Inc. 2014-2017 172


WSO2 API Cloud

You registered an organization and invited its members into the Cloud.

Block Subscription to an API

An API creator blocks subscription to an API as a way of disabling access to it and managing its usage and
monetization. A blocking can be temporary or permanent. You get an unblock option to allow API invocations
again.

In this tutorial, you block subscription to an API in the API Publisher and observe how the subscribers
can interact with it in the API Store. You also observe how the subscriber experience changes when you
unblock the API again.

You block APIs by subscriptions. That is, a given user is blocked access to a given API subscribed to using
a given application. If a user is subscribed to two APIs using the same application and you block access to
only one of the APIs, s/he can still continue to invoke the other APIs that s/he subscribed to using the same
application. Also, s/he can continue to access the same API subscribed to using different applications.

Blocking happens in two levels:

Block production and sandbox access: API access is blocked with both production and sandbox
keys.
Block production access only: Allows sandbox access only. Useful when you wants to fix and test
an issue in an API. Rather than blocking all access, you can block production access only, allowing
the developer to fix and test.

When the API Gateway caching is enabled (it is enabled by default), even after blocking a subscription,
consumers might still be able to access APIs until the cache expires, which happens approximately every 15
minutes.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

1. Log in to the API Publisher.


2. Create two APIs by the names TestAPI1 and TestAPI2 and publish them to the API Store.
3. Log in to the API Store. Click the APIs menu and note that the two APIs are visible in the APIs page.

Copyright © WSO2 Inc. 2014-2017 173


WSO2 API Cloud

4. Subscribe to both APIs using the same application. You can use an existing application or create a new one.

5. Click the APPLICATIONS menu, click the application that you used to subscribe to the API with ( DefaultAp
plication in this example), go to its Production Keys tab, and re-generate its access token. By default,
access tokens expire an hour after creation.application.

Copyright © WSO2 Inc. 2014-2017 174


WSO2 API Cloud

6. Invoke both APIs using the access token you got in the previous step. We use cURL here. The command is,

curl -k -H "Authorization: Bearer <access token>" '<API URL>'

Be sure to replace the placeholders as follows:

<access token>: Give the token generated in step 5


<API URL>: Go to the API's Overview tab in the API Store and copy the production URL and append
the payload to it.

Here's an example:

curl -k -H "Authorization: Bearer


f1d4d097-ebcc-3f02-8d91-0bd4e882ffcd"
'https://gateway.api.cloud.wso2.com:443/t/companyn3/test1/1.0.0/Check
PhoneNumber?PhoneNumber=18006785432&LicenseKey=0'

Copyright © WSO2 Inc. 2014-2017 175


WSO2 API Cloud

You have subscribed to two APIs and invoked them successfully. Let's block one subscription and see the
outcome.

7. Log back to the API Publisher.


8. Click MANAGE SUBSCRIPTIONS. It shows all APIs/applications that each user is subscribed to.

9. Block subscription for TestAPI1 using the DefaultApplication. Select the production and sandbox
option and click the Block link.

Copyright © WSO2 Inc. 2014-2017 176


9. WSO2 API Cloud

10. Note that the Block link turns to Unblock, allowing you to activate the subscription back at any time.
11. Invoke the two APIs (TestAPI1 and TestAPI2) again.

You might have to regenerate the access token for DefaultApplication as done in step 5, if
the access token expiration time (1 hour by default) has passed since the last time you generated it.

12. Note that you can invoke TestAPI2 again but when you invoke TestAPI1, it gives a message that the
requested API is temporarily blocked. Neither the API creator nor any subscriber can invoke the API until the
b l o c k i s r e m o v e d .

Tip: You might still be able to invoke an API within 15 minutes after blocking a subscription, until the
cache is renewed.

13. Back in the API Store, click the APPLICATIONS menu, select the application that you used to subscribe to
the two APIs earlier, click its Subscriptions tab, and note that your subscription is now blocked.

Copyright © WSO2 Inc. 2014-2017 177


WSO2 API Cloud

You can go to the API Publisher and unblock the subscription anytime. You have subscribed to two APIs, blocked
subscription to one and tested that you cannot invoke the blocked API.

Enable Self Signup to the API Store

By default, users who are not members of your organization cannot subscribe to and consume the APIs in your
default API Store. Only invited members can subscribe and use APIs. However, an admin of the organization
(tenant admin) can enable self sign-up to the API Store, allowing any visitor to the Store to register and become a
community member.

In this tutorial, you enable self sign-up to your API Store and observe how subscribers can register and
become community members. You then disable self signup.

Once self sign-up is enabled, users who visit your store can register to it themselves. When configuring self
sign-up, the tenant admin can select one of the following options:

Allow the registration requests to be approved automatically.


Make the registration requests to go through an approval process first.

Let's get started. See the video tutorial here or a step-by-step walk-through of the video tutorial below.

Here's a step-by-step walk-though of the video tutorial:

Copyright © WSO2 Inc. 2014-2017 178


WSO2 API Cloud

1. Log in to the API Cloud as the tenant admin.


2. The API Publisher opens. Click the Configure -> API Store Access menu.

3. Fill in the form that opens and click Configure. The parameters are described below.

Parameter Description

Signature An email is sent to the users who self sign up to the API Store. Give the name that you want to
line appear as the sender of this email.

Contact Give an email using which the new registrants can contact the admin if in case they need further
email assistance.

Tip: To edit this value later, change the fromAddress and contactEmail attributes
under the <UserSignUp> element in the registry resource /_system/governance/ap
imgt/applicationdata/workflow-extensions.xml.

Approval Select either of the two options:


process Send sign-up requests to me for approval- tenant admin approves or rejects sign-up
requests.
Automatically approve new members- sign-up requests are approved automatically.

Your Tenant admin's password.


password

You can customize the invitation emails for self sign-up users by applying your own logo and
changing the content. For information on how to do this, see Customize invitation emails.

Copyright © WSO2 Inc. 2014-2017 179


WSO2 API Cloud

4. You get a configuration successful notification. Click the API Store link in it to go to the API Store.
Alternatively, you can access the API Store using the URL https://api.cloud.wso2.com/store/?ten
ant=<your organization name>.

5. Log out of the API Store if you are logged in already and note the Sign-up link that appears in the upper
right-hand corner of the console.

Tip: It can take up to 15 minutes for the configuration changes to take effect. Therefore, you might

Copyright © WSO2 Inc. 2014-2017 180


WSO2 API Cloud

not see the Sign-up link immediately.

You have successfully configured the API Store for self sign-up. Let's register to the API Store as a visitor.

6. Click the Sign-up link and as an external API consumer who wants to use your APIs, give a new email
address to sign up to the Store.

Tip: You can get a temporary email address from http://www.fakemailgenerator.com/ to try out these
steps.

7. Check the tenant admin's email account that is used to log in to the Cloud. It will have a user sign-up
notification, which has a link to the WSO2 Cloud's Admin Dashboard. Click it and log in to the Admin
Dashboard using your tenant admin credentials.

Copyright © WSO2 Inc. 2014-2017 181


7.
WSO2 API Cloud

Note that if you select the option to allow automatic approval of new registration requests in step 2,
the following steps in this tutorial are not necessary.

Tip : You can find a link to the Admin Dashboard in the top menu bar of the API Publisher.

8. The Approval Tasks page opens. Click the Start button next to the registration request to approve it.

9. Select Approve from the drop-down list and click Complete.

The registration request is now approved.


10. Check the newly registered user's email that you gave in step 6 and note that you have a welcome email. It
has a one-time registration link. Click it.
11. Complete the registration process by providing a password in the form that opens.

Tip: If the email you used to sign up with has already been used in a different company (tenant
space) of the Cloud, you will not get the following page as you already have a password. Instead, you
will be directly navigated to the Cloud's login page.

Copyright © WSO2 Inc. 2014-2017 182


WSO2 API Cloud

12. Log in to the API Store and note that you can subscribe to and consume published APIs as a registered user.
Now, let's see how you can disable self sign-up.
13. Log in to the API Gateway's management console using the URL https://gateway.api.cloud.wso2.com/carbon
/admin/login.jsp. Copy your username from the top right-hand corner of the API Publisher. Use the same
password that you used to log in to WSO2 Cloud.
14. After logging in, click the Browse menu under the Resources menu.

15. When the API Gateway's registry opens, navigate to the registry resource /_system/governance/apimgt
/applicationdata/sign-up-config.xml.

Copyright © WSO2 Inc. 2014-2017 183


WSO2 API Cloud

16. Click Edit as text to edit the sign-up-config.xml file and set the <EnableSignup> element to false.

17. Go to the API Store using the URL https://api.cloud.wso2.com/store/?tenant=<your


organization name>, log out from it if you are logged in already and note that the Sign-up link is not
available anymore.

Tip: It can take some time for self sign-up to be disabled after you change the registry. This is

Copyright © WSO2 Inc. 2014-2017 184


WSO2 API Cloud

because the previous settings stay in cache until it is refreshed, which happens in every 15 minutes.

In this tutorial, you have configured self sign-up in the API Store as the tenant admin and registered to the API Store
as an anonymous user. You then disabled self sign-up and noticed how the Sign-up link doesn't appear anymore in
the API Store.

Authenticate Users that are External to WSO2 Cloud

There are different types of users who use your APIs in WSO2 API Cloud. Sometimes, some of these users might
not exist in the Cloud's user store such as the typical API publisher or subscriber. For example, the users of a typical
mobile application reside in a user store such as an LDAP or a database that is external to WSO2 Cloud. You
authenticate these external users as subscribers by registering the external user store as a secondary user store in
WSO2 Cloud.

Expand to see details of the authentication process of external subscribers...

Copyright © WSO2 Inc. 2014-2017 185


WSO2 API Cloud

1. The application invokes the Token API by passing the user's username and password.

2. The API Gateway checks whether the user exists in the primary user store, which is the WSO2 Cloud user
store. If the user is not there, it checks whether there is a secondary user store and if the user exists there. If
so, the Gateway checks whether the username and password are valid.

3. The user store performs the check and reports success or failure.

4. If authentication is successful, the API Gateway generates an OAuth token and passes it back to the
application.

5. For all subsequent actual API calls, the application passes the OAuth token in the Authorization header.

6. The Gateway checks the token to authorize the call and passes to the back end user identity information in
the form of a JWT token.

In this tutorial, you learn how to authenticate subscribers who are not in the WSO2 Cloud's user store.

Let's get started:

1. Log in to WSO2 API Cloud, click the Support link in the top menu bar, and submit a support request with the
following information:

User store type Submit details

LDAP (e.g., OpenLDAP, Microsoft Access URL and credentials


Active Directory)

Copyright © WSO2 Inc. 2014-2017 186


WSO2 API Cloud

Non-LDAP A Restful authentication service with:

The Restful service endpoint.

The basic authentication information, if the service is secured.

The JSON request and response body for WSO2 to configure the
server to work with your schema.

2. WSO2 adds your external user store as a secondary user store to WSO2 API Cloud and informs you. The
users in this secondary user store has permission to invoke APIs in your tenant domain.

3. Invoke the following cURL command to generate an access token for a user via the Token API.

Tip: The Token API allows you to generate and renew user and application access tokens. The
response of the Token API is a JSON message. You extract the token from the JSON and pass it
with an HTTP Authorization header to access APIs in the API Store.

curl -k -d
"grant_type=password&username=<username@organization_name>&password=<
PASSWORD>" -H "Authorization: Basic <Base64Encoded Consumer
key:consumer secret>" https://gateway.api.cloud.wso2.com/token

Copyright © WSO2 Inc. 2014-2017 187


WSO2 API Cloud

Tip: When passing the username, take the username that the user has in your system and add
"@<organization name that you have in the Cloud>" to the end.

For example, if the username in your database is testuser and the organization name in WSO2 Cloud
is my_company, then the username that you pass in the Token request is testuser@my_company.

Tip: To get the Consumer key and Consumer secret pair, go to the API Store and click the My
Subscriptions menu in the top menu bar. The Subscriptions page that opens has the keys.

4. Using the OAuth access token that you got in the previous step, invoke an API in the API Cloud. For
example,

curl -k -X GET --header 'Accept: application/xml' --header


'Authorization: Bearer <OAuth token from step 3>'
'https://gateway.api.cloud.wso2.com/t/companyn/dmzdemo/1.0.0/jaxrs_ba
sic/services/customerservice/customers/123'

5. See the actual identity of the user in your user store by examining the JWT token that is passed with each
API call. The end user identity is passed in the “ http://wso2.org/claims/enduser” property as shown in the
example below:

Sample JWT Token


{
"typ":"JWT",
"alg":"NONE"
}{
"iss":"wso2.org/products/am",
"exp":1345183492181,
"http://wso2.org/claims/subscriber":"user.email.com@org",
"http://wso2.org/claims/applicationname":"app2",
"http://wso2.org/claims/apicontext":"/placeFinder",
"http://wso2.org/claims/version":"1.0.0",
"http://wso2.org/claims/tier":"Silver",
"http://wso2.org/claims/enduser":"jane"
}

You have now learned how to add your external user store as a secondary user store to WSO2 Cloud, and to
generate access tokens for the users using the Cloud's Token API.

Customize Invitation Emails

WSO2 Cloud enables you to customize the emails sent to users. You can customize the emails by adding your own
logo and changing the content in the emails. Following are the two types of emails that can be customized according
to your requirements.

1. Emails for invited users


2. Emails for self sign-up users

Copyright © WSO2 Inc. 2014-2017 188


WSO2 API Cloud

If you want to make your own customizations as demonstrated below, contact WSO2 API Cloud Support via a
support request or chat.

Emails for invited users

There are three types of invitation emails that are sent to members, depending on the role(s) selected:

1. Invitation for subscribers


2. Invitation for publishers
3. Invitation for users with other roles or multiple roles

The default invitation email, with the WSO2 logo and graphics, sent to the Subscriber and Publisher roles is in the
following format:

Copyright © WSO2 Inc. 2014-2017 189


WSO2 API Cloud

WSO2 API Cloud provides you a one-time link, which will be sent with the invitation. You can customize the content
of the email and choose where the one-time link should be included. The fields for the roles will be replaced
according to your selection. You can also include your own logo and graphics to customize the email further.

An example of a customized email (for users with multiple roles), is shown below:

Copyright © WSO2 Inc. 2014-2017 190


WSO2 API Cloud

Emails for self sign-up users

There are three types of emails sent to after the user configures self sign-up.

1. User notification email

This is an example of a user notification email


H i ,
The organization <organizaton-name> has not yet approved your request. We will notify you
w h e n i t ' s a p p r o v e d .
If you need any further clarification, please contact <tenant admin's emailaddress>
R e g a r d s ,
<tenant-admin's signature>

2. User rejection email

This is an example of a user rejection email


H i ,
We regret to inform you that <organizaton-name> has not accepted your request to sign up to
t h e i r A P I S t o r e
If you need any further clarification, please contact <tenant admin's emailaddress>
R e g a r d s ,
<tenant-admin's signature>

3. User approval email

Copyright © WSO2 Inc. 2014-2017 191


WSO2 API Cloud
3.

This is an example of a user approval mail


H i ,
We are pleased to inform you that <organizaton-name> accepted your sign-up request. Please
use the following link to log in to the API Store: <user-approval-link>.
If you need any further clarification, please contact <tenant admin's emailaddress>
R e g a r d s ,
<tenant-admin's signature>

The default email notification will be in the following format.

An example of a customized email(user notification) is shown below.

Copyright © WSO2 Inc. 2014-2017 192


WSO2 API Cloud

Copyright © WSO2 Inc. 2014-2017 193


WSO2 API Cloud

Analytics
This section explains how to view and analyze statistics relating to APIs deployed in WSO2 API Cloud, configure
alerts to monitor these APIs and detect unusual activity, manage locations via geo location statistics and to carry out
detailed analysis of logs relating to the APIs. See the topics below for detailed information about how these
monitoring activities are carried out.

Viewing API Statistics


Managing Alerts
Analyzing Logs

Viewing API Statistics


API statistics are provided in both the API Publisher and the API Store. First, invoke a few APIs to generate traffic
and see the statistics.

The gadgets listed below do not display real time statistics.They are refreshed in time intervals to display the
the latest statistics generated, and the data scripts used to update them may take 10-15 minutes to be
executed. Following are the time intervals each gadget is updated.

Gadget Time Interval

Last Update Time 10 minutes

API Latency Stats 1 hour

API Throttling Stats 1 hour

User Agent Stats 1 hour

Other Stats 15 minutes

The sections below explain how to access the statistical dashboards:

API Publisher statistics


API Store statistics

API Publisher statistics

Log in to the API Publisher. Anyone who can create and/or publish APIs can view API-level usage and subscription
statistics by clicking on a selected API and referring to its Versions and Users tabs.

Copyright © WSO2 Inc. 2014-2017 194


WSO2 API Cloud

Copyright © WSO2 Inc. 2014-2017 195


WSO2 API Cloud

Given below are the statistical dashboards that are available from the Statistics menu.

Copyright © WSO2 Inc. 2014-2017 196


WSO2 API Cloud

In each of the dashboards, you can choose to view all APIs. If you are an API creator, you see only the APIs you
have created. You can also select the time period for which you wish to view the statistics.

Several examples of usage and performance statistics are given below:

Published APIs Over Time


API Usage
API Response Times
API Last Access Times
Usage by Resource Path
Usage by Destination
API Usage Comparison
API Throttled Requests
Faulty Invocations

Copyright © WSO2 Inc. 2014-2017 197


WSO2 API Cloud

API Latency Time


API Usage Across Geo Locations
API Usage Across User Agent
App Throttled Requests
Applications Created Over Time
API Subscriptions
Developer Signups Over Time
Subscriptions Created Over Time

Published APIs Over Time

API Usage

Copyright © WSO2 Inc. 2014-2017 198


WSO2 API Cloud

API Response Times

API Last Access Times

Copyright © WSO2 Inc. 2014-2017 199


WSO2 API Cloud

Usage by Resource Path

Usage by Destination

API Usage Comparison

Copyright © WSO2 Inc. 2014-2017 200


WSO2 API Cloud

API Throttled Requests

Copyright © WSO2 Inc. 2014-2017 201


WSO2 API Cloud

Faulty Invocations

Copyright © WSO2 Inc. 2014-2017 202


WSO2 API Cloud

API Latency Time

Copyright © WSO2 Inc. 2014-2017 203


WSO2 API Cloud

API Usage Across Geo Locations

The data script that updates statistics related to geo locations is executed once a day. Therefore, at a
given time, some of the statistics generated within the last 24 hours may not be displayed in this
gadget.

API Usage Across User Agent

App Throttled Requests

Copyright © WSO2 Inc. 2014-2017 204


WSO2 API Cloud

Applications Created Over Time

Copyright © WSO2 Inc. 2014-2017 205


WSO2 API Cloud

API Subscriptions

Developer Signups Over Time

Copyright © WSO2 Inc. 2014-2017 206


WSO2 API Cloud

Subscriptions Created Over Time


You first need to select the API for which you wish to view subscriptions.

Copyright © WSO2 Inc. 2014-2017 207


WSO2 API Cloud

API Store statistics

Log in to the API Store. You can self-subscribe to the store. Next, click the Statistics menu.

Given below are the statistical dashboards that are available:

API Usage: The usage of the API per application


Top Users: Users who make the most API invocations per application
Resource Usage: Usage of an API and from which resource path per application

Copyright © WSO2 Inc. 2014-2017 208


WSO2 API Cloud

Faulty Invocations: Number of faulty API invocations per application


In a faulty API invocation, the message is mediated though the fault sequence. By default, the API
Manager considers an API invocation to be faulty when the backend service is unavailable.

Several examples of usage and performance statistics are given below:

API Usage per Application

Top Users per Application

Copyright © WSO2 Inc. 2014-2017 209


WSO2 API Cloud

Resource Usage per Application

Faulty Invocations per Application

Copyright © WSO2 Inc. 2014-2017 210


WSO2 API Cloud

Managing Alerts
The following topics cover the alert types available to monitor APIs and how to view them.

Alert Types
Subscribing for Alerts

Alert Types

The following alert types are currently supported for WSO2 API Cloud.

Abnormal response time


Abnormal backend time
Abnormal request count
Abnormal resource access
Unseen source IP address
Abnormal access token renewal
Tier crossing
Abnormal API usage
Health availability

Abnormal response time

Reason for triggering If there is a sudden increase in the response time of a


specific API resource.

Indication Slow WSO2 API Manager runtime, or slow backend.

Description If the response time of a particular API resource (e.g., G


ET /API1/1.0/user/1) of a tenant, lies outside the
Xth percentile value, an alert is sent. Default percentile
value is 95%. Here, it is assumed that the response
time of an API resource follows a normal distribution.
Percentile value gets calculated daily by default.

Abnormal backend time

Reason for triggering If there is a sudden increase in the backend time


corresponding to a particular API resource.

Indication Slow backend

Copyright © WSO2 Inc. 2014-2017 211


WSO2 API Cloud

Description An alert is sent if the backend time of a particular API


resource (e.g., GET /calc/1.0/numbers) of a tenant
lies outside the Xth percentile value. Default percentile
value is 95%. Here, it is assumed that the
corresponding backend time of an API resource follows
a normal distribution. The percentile value gets
calculated daily by default.

Abnormal request count

Reason for triggering If there is a sudden spike or a drop in the request count
within a period of one minute by default for a particular
API resource.

Indication These alerts can be considered indications of high


traffic, suspicious acts or the malfunction of client
applications etc.

Description An alert is sent if the number of requests received by a


particular API resource (e.g., GET /calc/1.0/numbers) of
a tenant of a particular application within the last minute
lies outside the Xth and Yth percentile values. The
default percentile values are 95% and 5%. Here, it is
assumed that the request counts received by an API
resource follows a normal distribution. Percentile value
(a per minute average request count value) gets
calculated daily by default.

Abnormal resource access

Reason for triggering If there is a change in the resource access pattern of a


user who uses a particular application.

Indication These alerts can be considered as indications of


suspicious activities done by one or more users in your
application.

Copyright © WSO2 Inc. 2014-2017 212


WSO2 API Cloud

Description A Markov Chain model is built for each application to


learn its resource access pattern. For the purpose of
learning the resource access patterns, no alerts are
sent during the first 500 (default) requests. After
learning the normal pattern of a specific application,
WSO2 Analytics performs a real time check on a
transition done by a specific user, and sends and alert
if it is identified as an abnormal transition.For a
transition to be considered valid, it has to occur within
60 minutes by default, and it should be by the same
user.

The above diagram depicts an example where a


Markov Chain model is created during the learning
curve of the system. Two states are recorded against
Application A and the arrows show the directions of the
transitions. Each arrow carries a probability value that
stands for the probability of a specific transition taking
place. Assume that the following two consecutive
events are received by the application from user john@
abc.com.

1. DELETE /API1/number/1
2. DELETE /API1/number/3

The above transition has happened from the DELETE


/API1/number/{x} state to itself. According to the
Markov chain model learnt by the system, the
probability of this transition occurring is very low.
Therefore, an alert is sent.

Unseen source IP address

Reason for Triggering If there is either a change in the request source IP for a
specific API of an application, or if the request if from
an IP used before 30 days (default).

Indication These alerts can be considered as indications of


suspicious activities carried out by a user over an API
of an application.

Copyright © WSO2 Inc. 2014-2017 213


WSO2 API Cloud

Description

The first 500 requests are used only for learning


purposes by default and therefore, no alerts are sent
during that time. However, the learning would continue
even after the first 500 requests. This means, even if
you receive continuous requests from the newly
detected IP2 IP, you are alerted only once.

Abnormal access token renewal

Reason for Triggering If there is a change in the access token renewal pattern
of a user.

Indication This alert can be considered as an indication that the


access token may be stolen.

Copyright © WSO2 Inc. 2014-2017 214


WSO2 API Cloud

Description In order to trigger this alert, you need to enable the Abs
tractIdentityHandler alert in the <IS_HOME>/re
pository/conf/identity/identity.xml file.

<!--EventListener
type="org.wso2.carbon.identity
.core.handler.AbstractIdentity
Handler"

name="org.wso2.carbon.identity
.data.publisher.oauth.listener
.OAuthTokenIssuanceDASDataPubl
isher"

orderId="11" enable="true"/>

When an access token is renewed, the system checks


whether the time interval between the time it was last
renewed and the current time. If this time duration is
outside the value defined by the upper and lower
percentile values (95% and 10% respectively by
default), an alert is triggered. Here is it assumed that
the access token renewal times of a particular
application by a particular user follows a normal
distribution. The percentile value (a time difference
between two consecutive renewals of an access token
of an application by a user) is calculated weekly by
default. Therefore, no alerts are sent during the first 7
days after the alert is configured.

Tier crossing

Copyright © WSO2 Inc. 2014-2017 215


WSO2 API Cloud

Reason for Triggering This alert is triggered in the following scenarios.

If a particular application is throttled for reaching a


subscribed tier limit more than the specified number
of times during a defined period (10 times within a
day by default).
If a particular user of an application is throttled for
reaching a subscribed tier limit of a specific API more
than the specified number of times during a defined
period (10 times within a day by default).

Indication These alerts indicate that you need to subscribe to a


higher tier.

Abnormal API usage

Reason for Triggering If there is a drastic reduction in API usage by a specific


user for a given API.

Indication These alerts indicate the failure of the application that


is using the altered API.

Description For the purpose of detecting abnormal API usage, it is


assumed that API requests are normally distributed.
The mean and the variance are the two main properties
of a normal distribution. These are calculated per user
for each application. Instead of using all the past
requests, you can define a time period based on which
the mean and variance should be calculated. The
default time period is 30 days.

Health availability

These alerts are triggered for the reasons specified in the tables below.

Reason for Triggering The response time of an API is greater than the upper
percentile value specified for the same (which is 95 by
default). This should occur continuously for a specified
number of times (5 times by default).

Indication The response time is too high.

Copyright © WSO2 Inc. 2014-2017 216


WSO2 API Cloud

Reason for Triggering The request count of an API per minute is less than the
lower percentile value specified for the same (which is
5 by default). This should occur 5 times (i.e. 5 minutes)
continuously in order to trigger the error.

Indication The request count per minute is normal, but the


response count per minute is low.

Reason for Triggering The response status code is less than or equal to 500,
but less than 600. This should occur continuously for a
specified number of times ( 5 by default) in order to
trigger an alert.

Indication A server side error has occurred.

Subscribing for Alerts

The subscriptions for alerts can be created by system administrators as well as publishers and subscribers. The
alert types available for subscriptions depends on the role. Click on the relevant tab for the procedure to subscribe
for alerts based on your role.

System Administrators
Publishers
Subscribers

A system administrator is allowed to select one or more alert types to subscribe for, as well as specify a list of email
addresses to which the alerts should be sent. Follow the procedure below to carry out the tasks mentioned above
using the Admin Portal of WSO2 API Cloud.

1. Access the WSO2 API Cloud Admin portal with the https://api.cloud.wso2.com/admin URL, and log
in with your credentials.
2. Expand Analytics in the left navigator and click MANAGE ALERT TYPES to open the Manage Alert Types
page.

Copyright © WSO2 Inc. 2014-2017 217


WSO2 API Cloud

3. Select the relevant check boxes based on the alert types to which you want to subscribe.
4. In the Email field, enter a list of email addresses to which the selected alerts should be sent.
5. Click Save to save the information.

An API Cloud publisher can enable/disable alert types based on the alerts that he/she wants to receive individually,
as well as specify a list of email addresses to which the alerts should be sent.

1. Access the WSO2 API Cloud Publisher with the https://api.cloud.wso2.com/publisher URL, and
log in with your credentials.
2. In the left navigator and click MANAGE ALERT TYPES to open the Manage Alert Types page.

Copyright © WSO2 Inc. 2014-2017 218


WSO2 API Cloud

3. Select the relevant check boxes based on the alert types to which you want to subscribe.
4. In the Email field, enter a list of email addresses to which the selected alerts should be sent.
5. Click Save to save the information.

An API Cloud subscriber can enable/disable alert types based on the alerts that he/she wants to receive individually,
as well as specify a list of email addresses to which the alerts should be sent.

1. Access the WSO2 API Cloud Store with the https://api.cloud.wso2.com/store URL, and log in with
your credentials.
2. In the left navigator and click MANAGE ALERT TYPES to open the Manage Alert Types page.

3. Select the relevant check boxes based on the alert types to which you want to subscribe.
4. In the Email field, enter a list of email addresses to which the selected alerts should be sent.
5. Click Save to save the information.

Copyright © WSO2 Inc. 2014-2017 219


WSO2 API Cloud

Analyzing Logs
Follow the steps below to vie reports in the Log Analyzer.

1. Access the WSO2 API Cloud Admin portal with the https://api.cloud.wso2.com/admin URL, and log
in with your credentials.
2. In the left navigator, click Log Analyzer to expand the Log Analyzer section. Then click on one of the
following depending on the information you want to view.

LIVE LOG VIEWER: To view logs that are currently being generated. For more information about how
to use the gadgets in this page, see Viewing Live Logs.
OVERVIEW: To view the overall statistics for each log category generated. For more information about
how to use the gadgets in this page, see Analyzing the Log Overview.
APPLICATION ERRORS: To view detailed information about different categories of errors that have
occurred. For more information about how to use the gadgets in this page, see Analyzing Application
Errors.
API DEPLOYMENT STATS: To view overall statistics relating to all the APIs that are deployed in
WSO2 API Manager. For more information about how to use the gadgets in this page, see Analyzing
API Deployment Statistics.
LOGIN ERRORS: To view overall statistics for login errors that have occurred for your WSO2 API
Manager installation. For more information about how to use the gadgets in this page, see Analyzing
Login Errors.
NUMBER OF API FAILURES: To view statistics relating to instances where the APIs deployed in your
WSO2 API Manager installation have failed. For more information about how to use the gadgets in this
page, see Analyzing the Number of API Failures.

Viewing Live Logs

Introduction
Purpose

Copyright © WSO2 Inc. 2014-2017 220


WSO2 API Cloud

Recommended action

Introduction

The Live Log Viewer in the API-M Admin Portal views the latest 100 logs collected from a WSO2 API Manager at
any given time. The following is a sample log viewed in the Live Log Viewer. The logs are displayed in the order in
which they are generated since the initial page loading. The latest log appears at the bottom. The information
displayed on this page gets refreshed in every 5 seconds time.

Purpose

This gadget allows you to view logs online with detailed information in the order in which they were generated.

Recommended action

To view logs for specific activities, check the Live Log Viewer immediately after you carry them out.

Analyzing the Log Overview

Introduction
Purpose
Recommended Action

Copyright © WSO2 Inc. 2014-2017 221


WSO2 API Cloud

At any given time, this page displays the statistics for a selected time interval.

If you want to view statistics for a pre-defined time interval, click on the relevant time interval (e.g., La
st 30 Days).

If you want to define a custom time interval, click Custom and select the start and end dates of the
required time interval in the calendar that appears. Then click Apply.

Introduction

This page displays the overall statistics for all the available types of log events (i.e. INFO, DEBUG, ERROR, WARN
and FATAL) that were created during the selected time interval. The information displayed allows you to understand
the overall health of the API Manager installation. The exact count for each log event type can be viewed by moving
the cursor over the relevant bar. The following is an example of this report.

Purpose

This gadget allows you to:

Check the count for each type of log event at different time intervals in order to identify any correlation
between frequency of their occurrence and time.
Compare the count for different types of log events.

Copyright © WSO2 Inc. 2014-2017 222


WSO2 API Cloud

Recommended Action

If the count for log events of ERROR and FATAL types are particularly high at a specific time, carry out further
investigations for unusual occurrences (e.g., API failure corresponding to the same time interval(s)).
If the count for log events of ERROR, WARN and FATAL is always high, recheck the configurations for your
WSO2 API Manager installation and do the necessary changes to improve the overall health of your setup.
Compare the count for different type of log events different times and identify any patterns relating to the
correlation between the occurrence of log events and time. When major deviations from these patterns are
identified, carry out further investigations to identify the causes (e.g., increase/decrease in the load handled
by WSO2 API Manager.).

Analyzing Application Errors

Introduction
Purpose
Recommended action

At any given time, this page displays the statistics for a selected time interval.

If you want to view statistics for a pre-defined time interval, click on the relevant time interval (e.g., La
st 30 Days).

If you want to define a custom time interval, click Custom and select the start and end dates of the
required time interval in the calendar that appears. Then click Apply.

Introduction

This page displays information relating to application errors that have occurred in the WSO2 API Manager.

Errors Distribution

Copyright © WSO2 Inc. 2014-2017 223


WSO2 API Cloud

This gadget displays the count of application errors for each day/time over the selected time interval in a bar chart
as shown in the example below. Each bar provides a breakdown of errors based on their exception category. If you
move the cursor over a specific category, the following information is displayed as demonstrated above.

ID: The ID of the exception category.


Count: The number of times an exception belonging to the exception category has occurred.
Day: The date on which the exception occurred.

Filtered Messages

Copyright © WSO2 Inc. 2014-2017 224


WSO2 API Cloud

If you click on a coloured block representing an exception category, the Filtered Messages section is populated
with details of all the individual occurrences of that exception category as shown above. At a give time, it displays
only messages that belong to a selected category. You can sort the records in this table in the
ascending/descending order based on the time stamp.

Log viewer

Copyright © WSO2 Inc. 2014-2017 225


WSO2 API Cloud

If you want to view more details about an individual exception occurrence displayed in the Filtered Messages secti
on, click View on the relevant row. As a result, the Log Viewer section displays the log in which the exception was
recorded, including the 100 rows that were logged before the exception as well as the 100 rows that were logged
after the exception. Different log levels are highlighted in different colours (i.e. ERROR level in red, WARN level in
yellow, and INFO level in blue).

Purpose

This page allows you to:

Identify the exception categories that have occurred for you APIM Manager installation for different time
intervals.
Compare counts for different exception categories during selected time intervals.
Check detailed information relating to each exception to identify its cause.
Identify related logs for each exception to identify its cause.

Recommended action

Observe the most frequently occurring exception categories. Identify their causes and take corrective action
(e.g., configuration corrections etc.)

Copyright © WSO2 Inc. 2014-2017 226


WSO2 API Cloud

Compare counts for exception categories for different time intervals. If the count is high for any exception
category at specific time intervals, check whether any unusual activity has taken place during that time (e.g.,
system downtime).

Analyzing API Deployment Statistics

Introduction
Purpose
Recommended Action

At any given time, this page displays the statistics for a selected time interval.

If you want to view statistics for a pre-defined time interval, click on the relevant time interval (e.g., La
st 30 Days).

If you want to define a custom time interval, click Custom and select the start and end dates of the
required time interval in the calendar that appears. Then click Apply.

Introduction

This page shows the artifacts that were deployed as well as the artifacts that were deleted during the selected time
period. It also indicates the number of times each artifact was deployed/deleted. In each gadget, you can search for
a specific API and sort the APIs in the ascending/descending order by the available fields

Copyright © WSO2 Inc. 2014-2017 227


WSO2 API Cloud

Purpose

This page allows you to:

View statistics for all the APIs deployed in your WSO2 API Manager installation.
Check the status for each API (i.e. whether it is available for use or deleted).
Understand the extent to which each API is used by checking the frequency with which they were
deployed/deleted.

Recommended Action

Compare the frequency with which different APIs are deployed/deleted to identify the most frequently used APIs.

Analyzing Login Errors

Introduction
Purpose
Recommended action

At any given time, this page displays the statistics for a selected time interval.

If you want to view statistics for a pre-defined time interval, click on the relevant time interval (e.g., La
st 30 Days).

If you want to define a custom time interval, click Custom and select the start and end dates of the
required time interval in the calendar that appears. Then click Apply.

Copyright © WSO2 Inc. 2014-2017 228


WSO2 API Cloud

Introduction

This page indicates the number of login attempt failures that have occurred during the selected time interval in a bar
chart as shown in the example below. The exact count for a specific unit of time (e.g., day, hour, etc.) can be viewed
by moving the cursor over the relevant bar.

Purpose

This page allows you to identify the time periods during which login errors have occurred to understand what caused
them.

Recommended action

Compare the count for failed login errors at different time intervals. If the count is particularly high during specific
time intervals, check for any unusual occurrences that may have taken place during that time (e.g., system
downtime). If a high count for login errors is observed for all time intervals, check the relevant configurations in
WSO2 API Manager (e.g., configuration of users and user roles).

Analyzing the Number of API Failures

Introduction
Purpose
Recommended Action

At any given time, this page displays the statistics for a selected time interval.

If you want to view statistics for a pre-defined time interval, click on the relevant time interval (e.g., La
st 30 Days).

If you want to define a custom time interval, click Custom and select the start and end dates of the
required time interval in the calendar that appears. Then click Apply.

Copyright © WSO2 Inc. 2014-2017 229


WSO2 API Cloud

Introduction

This report indicates the number of API failures that have occurred during the selected time interval. Each API is
represented by a different colour. To check the exact failure count for an API on a specific date, move the cursor
over the relevant colour block as demonstrated below.

Purpose

This page allows you to:

Check the API failure count at different time intervals, and identify any correlations that may exist between
API failure and time.
Compare the number of failures for different APIs and identify APIs with highest number of failures and
identify the corrective action that needs to be taken.

Recommended Action

Identify time intervals with the highest API failure counts and investigate further to find the causes.
Identify APIs with the highest number of failures and investigate further by checking logs relating to these
APIS to find the causes, and take corrective action (e.g., correct the message formats).

Copyright © WSO2 Inc. 2014-2017 230


WSO2 API Cloud

Cloud Administration
Click a topic to see how to perform the task:

[ Add a new organization ] [ Customize your production URLs ] [ Add members to your organization ]

Add a new organization

If you have already signed up to WSO2 Cloud and you want to add a new organization using the same email
address, do the following:

1. Log in to the organization that you are already registered to in WSO2 Cloud.
2. Click the settings icon in the upper, right-hand corner of the UI and click Organizations.

3. In the Manage Organizations page that opens, click Add Organization to create a new organization.

Customize your production URLs

To change the production URLs to something that is more representative of your company or personal branding, clic
k the settings icon in the upper, right-hand corner of the UI and click Custom URL.

Copyright © WSO2 Inc. 2014-2017 231


WSO2 API Cloud

For a detailed tutorial, see Customize Cloud URLs.

Add members to your organization

When you register to the Cloud, you become the admin of your organization. You can add new members and assign
them different roles. Click the settings icon in the upper, right-hand corner of the UI and click Members.

Copyright © WSO2 Inc. 2014-2017 232


WSO2 API Cloud

For a detailed tutorial, see Register and Invite Members.

Copyright © WSO2 Inc. 2014-2017 233


WSO2 API Cloud

WSO2 APIs
If you want to programmatically invoke the functions of the Cloud, here's a list of APIs that are available:

Common Cloud APIs


Publisher APIs
Store APIs
Token API

Common Cloud APIs


The following Cloud APIs are available:

[ Login ] [ addUserToTenant ] [ deleteUserFromTenant ]

Note: Before you add or delete users from your tenant, you must first log in to your tenant space in the
Cloud as admin.

Login

Description Log in to WSO2 Cloud's tenant space as admin.

URI https://cloudmgt.cloud.wso2.com/cloudmgt/site/blocks/user/authenticate/ajax/login.j

URI
Parameters action: login
userName: Admin's username

password: Password of the admin

HTTP POST
Methods

Example curl -c cookies -k -v -X POS


https://cloudmgt.cloud.wso2.com/cloudmgt/site/blocks/user/authenticate/ajax/login.j
-d 'action=login&userName=<user name> &password=adminpassword'

The <user name> should be email@organization_key. For example, if the e-mail


is jhon@gmail.com, the <user name> should be jhon@gmail.com@organization_key. You can find
the organization_key on the Manage page of the cloud.

addUserToTenant

Description Create a new user in the Cloud

URI https://cloudmgt.cloud.wso2.com/cloudmgt/site/blocks/tenant/users/add/ajax/add.jag

Copyright © WSO2 Inc. 2014-2017 234


WSO2 API Cloud

URI
Parameters action: addUserToTenant
userEmail: Email address of the user
password: User's password should meet at least three of the below criteria:
Uppercase letters
Lowercase letters
Numbers
Special characters
firstName: User's first name (alphanumeric characters only)
lastName: User's last name (alphanumeric characters only)
roles: User's roles. Can take one or more of the following roles in a comma-separated list: integrationclouduser

HTTP POST
Methods

Example curl -k -v -X POST https://cloudmgt.cloud.wso2.com/cloudmgt/site/block


'Content-Type:application/x-www-form-urlencoded' -H
'action=addUserToTenant&userEmail=myemail@wso2.com&password=testPassword&firstName=

deleteUserFromTenant

Description Delete an existing user from your tenant

URI https://cloudmgt.cloud.wso2.com/cloudmgt/site/blocks/tenant/users/add/ajax/add.jag

URI
Parameters action: deleteUserFromTenant
userName: Email address of the user

HTTP POST
Methods

Example curl --b cookies --k -v


POST https://cloudmgt.cloud.wso2.com/cloudmgt/site/blocks/tenant/users/add/ajax/add
--H 'Content-Type:application/x-www-form-urlencoded' -H 'Accept-Language:en-US,en;
'action=deleteUserFromTenant&userName=myemail@wso2.com'

Publisher APIs

Note that the REST APIs listed on this page are deprecated. Click https://docs.wso2.com/display/AM210/api
docs/publisher for the recommended list of Publisher APIs.

Publisher APIs provide the following REST resources.

[ Login ] [ Logout ] [ Add API ] [ Update API ] [ Get All APIs ] [ Get an API ] [ Remove an API ] [ Copy an API ] [ Check Old
er Version ] [ Change API Status ] [ Add/Update an API Document ] [ Remove an API Document ] [ Get all Throttling
Tiers ] [ Check if API Exists ] [ Validate Roles ] [ Get List of API Creators ] [ Get Subscriber Count ] [ Get API Usage By
Resource Path ] [ Get API Usage By Destination ] [ Get API Usage by Provider ] [ Get API and Application Throttling
Data ] [ Get API Response Fault Count ]

Note: When you access any API other than the login and logout APIs through an external REST client such

Copyright © WSO2 Inc. 2014-2017 235


WSO2 API Cloud

as cURL, first invoke the login API to ensure that user is authenticated. When the login API is invoked, the
system stores the generated session cookie in a file, which we use in the next API invocations.

The responses is a JSON message.

Login

Description Log in to API Publisher web application.

URI https://api.cloud.wso2.com/publisher/site/blocks/user/login/ajax/login.jag

URI action=login&username=xxx&password=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -c cookies https://api.cloud.wso2.com/publisher/site/blocks/user/login/ajax/login.jag -d


'action=login&username=<user name>&password=xxx'

The <user name> should be email@organization_key. For example, if the e-mail is jhon@gmail.co
m, the <user name> should be jhon@gmail.com@organization_key. You can find the
organization_key on the Manage page of the cloud.

Logout

Description Log out from API Publisher web application.

URI https://api.cloud.wso2.com / publisher/site/blocks/user/login/ajax/login.jag

URI ?action=logout
Parameters

HTTP GET
Methods

Example curl -b cookies https://api.cloud.wso2.com / publisher/site/blocks/user/login/ajax/login.jag ?actio


n=logout

Add API

Description Add a new API.

URI https://api.cloud.wso2.com / publisher/site/blocks/item-add/ajax/add.jag

URI Given below are the parameters that you can pass with an Add-API call. Mandatory ones are marked with a *.
Parameters

Parameter Syntax
name

Action* action=addAPI

Copyright © WSO2 Inc. 2014-2017 236


WSO2 API Cloud

Name* name=xxx

Context* context=/xxx

Version* version=x.x.x

API visibility visibility=<public|private|restricted>

The default is public. If you select restricted , mention to which roles as follows: visibilit

You can read more about API visibility from here.

Thumbnail
image To add a thumbnail image as a file object, create the object and pass it with the apiThumb pa
To add a thumbnail image as a URL of the image, pass the URL with the thumbUrl parame

Description description=xxx

Tags tags=x,y,z

Resources* resourceCount=0&resourceMethod-0=GET&resourceMethodAuthType-0=Application&resource

resourceMethod can take any one of the following values: GET, POST, DELETE, PUT, OP
resourceMethodAuthType can take any one of the following values: Application, Applicati
resourceMethodThrottlingTier can take any one of the following default values: Unlim

Copyright © WSO2 Inc. 2014-2017 237


WSO2 API Cloud

Resources Instead of adding resources directly as above, you can add resources, including scopes, as a S
as Swagger

swagger={"paths" : {"/CheckPhoneNumber" : {"post" : {"x-auth-type


"Application%20%26%20Application%20User", "x-throttling-tier" : "
"in" : "query"}, {"name" : "LicenseKey", "paramType" : "query", "
"swagger" : "2.0", "x-wso2-security" : {"apim" : {"x-wso2-scopes"

In the above code, note that you have one resource path defined with the URL pattern /Check
HTTP method, you can define several parameters.

For more information of the Swagger objects used in this example, see the Swagger 2.0 specifi

x-wso2-scopes: The list of scope elements that you want to define. Each element has the be
description: Scope description
roles: Allowed roles
name: Scope Name
key: Scope Key
x-auth-type: Authentication type of the method.
x-throttling-tier: Throttling tier of the method.
x-scope: OAuth scope of the method. This must be one of the list of element you define in x-w

The following image shows the WSO2-specific parameters we describe here. Also see Resourc

Endpoints* This example adds an HTTP production endpoint: endpoint_config={"production_endp

To give advanced endpoint configurations, add the JSON implementation inside "config:{}." If yo

You add sandbox endpoints in the same way. The only difference is that instead of productio

If you want to add other types of endpoints, follow the examples below. Note that the endpoin

For address endpoints:


endpoint_config={"production_ endpoints":{"url":" https://service.end
For failover endpoints:
endpoint_config={"production_ endpoints":{"url":" https://service.end
"sandbox_failovers":[]," endpoint_type":"failover"}
For load balanced endpoints:
endpoint_config" {"production_endpoints":[{" url":" https://service.e
"algoClassName":"org.apache. synapse.endpoints.algorithms. RoundRobin

Endpoint endpointType=<secured|nonsecured>
security
scheme The default is non-secured but if you select 'secured', you must pass the credentials as follows:

Copyright © WSO2 Inc. 2014-2017 238


WSO2 API Cloud

Make default To mark this version of the API as the default version from a group of versions, give default
version
The Default Version option means that you make this version the default in a group of differen
/host:port/youtube/ get automatically routed to version 2.0.

If you mark any version of an API as the default, you get two API URLs in its Overview page in

If you mark an unpublished API as the default, the previous default, published API will still be us

Tier tiersCollection=<Gold,Silver,Bronze,Unlimited>
Availability*

Transports http_checked=http&https_checked=https

Both are selected by default. If you want to set only the HTTP transport, leave the https_che

Sequences If you want to engage a custom sequence to the API, give inSequence=<sequence name>&

Response responseCache=<enabled|disabled>
caching
It is disabled by default but if you enable it, pass the response cache timeout as follows: respo

See Response Caching for more information.

Subscriptions By default, subscription is allowed to the current tenant only.

Add the argument subscriptions=all_tenants to enable subscriptions to this API by all

See API visibility and subscription for more information.

Business Add a section like this: bizOwner=<name>&bizOwnerMail=<e-mail address>&techOwn


information

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com


number&tags=phone,mobile,multimedia&endpointType=nonsecured&tiersCollection=Gold,Bronze&http_checked
xx@ee.com &techOwner=xx&techOwnerMail= ggg@ww.com " -d'endpoint_config={"production_endpoints":{"url"

Update API

Description Update an existing API

URI https://api.cloud.wso2.com / publisher/site/blocks/item-add/ajax/add.jag

URI Parameters are same as in Add API except that a ction= updateAPI and you can only update the following p
Parameters tags, endpointType, endpoint_config (can change the endpoint URL etc,) http_checked, https_checked, tiersC
resources. See example below.

Copyright © WSO2 Inc. 2014-2017 239


WSO2 API Cloud

HTTP POST
Methods

Example Update API : curl -X POST -b cookies https://api.cloud.wso2.com / publisher/site/blocks/item-add/ajax/add.jag -d


ion&provider=admin&version=1.0.0&visibility=public&description=Youtube
Feeds&endpointType=nonsecured&http_checked=http&https_checked=https&tags=youtube,gdata,multimedia&t
as.com.au/www/573/files/pf-thumbnail-youtube_logo.jpg&context=/youtube&tiersCollection=Gold,silver&resource
ceMethodAuthType-0=Application&resourceMethodThrottlingTier-0=Unlimited&uriTemplate-0=/*" -d'endpoint_c
gdata.youtube.com/feeds/api/standardfeeds","config":null},"endpoint_type":"http"}';

Get All APIs

Description Lists all the created APIs.

URI https://api.cloud.wso2.com / publisher/site/blocks/listing/ajax/item-list.jag

URI ?action=getAllAPIs
Parameters

HTTP GET
Methods

Example curl -b cookies https://api.cloud.wso2.com/publisher/site/blocks/listing/ajax/item-list.jag ?action=g


etAllAPIs

Get an API

Description Get details of a specific API.

URI https://api.cloud.wso2.com/publisher/site/blocks/listing/ajax/item-list.jag

URI action=getAPI&name=xxx&version=xxx&provider=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/publisher/site/blocks/listing/ajax/item-list.jag -d


'action=getAPI&name=API1&version=1.0.0&provider=user1'

Remove an API

Description Remove an API.

URI https://api.cloud.wso2.com / publisher/site/blocks/item-add/ajax/remove.jag

URI action=removeAPI&name=xxx&version=xxx&provider=xxx
Parameters

HTTP POST
Methods

Copyright © WSO2 Inc. 2014-2017 240


WSO2 API Cloud

Example curl -X POST -b cookies https://api.cloud.wso2.com /


publisher/site/blocks/item-add/ajax/remove.jag -d
'action=removeAPI&name=API1&version=1.0.0&provider=user1'

Copy an API

Description Copy an API to a newer version.

URI https://api.cloud.wso2.com / publisher/site/blocks/overview/ajax/overview.jag

URI action=createNewAPI&provider=xxx&apiName=xxx&version=xxx&newVersion=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com / publisher/site/blocks/overview/ajax/overv


"action=createNewAPI&provider=user1&apiName=API1&version=1.0.0&newVersion=2.0.0&isDefaultVersion=de

Check Older Version

Description Does older version of API exist.

URI https:// api.cloud.wso2.com / publisher/site/blocks/life-cycles/ajax/life-cycles.jag

URI action=isAPIOlderVersionExist&provider=xxx&name=xxx&version=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https:// api.cloud.wso2.com /


publisher/site/blocks/life-cycles/ajax/life-cycles.jag ?action=isAPIOlderVersion
Exist&provider=user1&name=API1&version=1.0.0

Change API Status

Description Change the API's status.

URI https:// api.cloud.wso2.com / publisher/site/blocks/life-cycles/ajax/life-cycles.jag

URI action=updateStatus&name=xxx&version=1.0.0&provider=apiCreateName&status=PUBLISHED&publishToGate
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/publisher/site/blocks/life


'action=updateStatus&name=TwitterAPI&version=1.0.0&provider=provider&status=PUBLISHED&publishToGate

Add/Update an API Document

Description Add a new API document.

Copyright © WSO2 Inc. 2014-2017 241


WSO2 API Cloud

URI https://api.cloud.wso2.com / publisher/site/blocks/documentation/ajax/docs.jag

URI A d d
Parameters action=addDocumentation&provider=xxx&apiName=xxx&version=xxx&docName=xxx&docType=xxx&sourceTyp

Add Document file: action=addDocumentation&provider=xxx&apiName=xxx&version=xxx&docName=xxx&docT

U p d a t e
action=addDocumentation&mode=Update&provider=xxx&apiName=xxx&version=xxx&docName=xxx&docType=

HTTP POST
Methods

Example Add Document: curl -X POST -b cookies https://api.cloud.wso


"action=addDocumentation&provider=admin&apiName=PhoneVerification&version=1.0.0&docName=testDoc&do

Add Document file: curl -X POST -b cookies https://api.cloud.wso2.com / publisher/site/blocks/documentation/a


-F "version=1.0.0" -F "docName=testDoc2" -F "docType=how to" -F "sourceType=file" -F "docUrl=" -F "summary=

Update Document: curl -X POST -b cookies https://api.cloud.ws


"action=addDocumentation&mode=Update&provider=admin&apiName=PhoneVerification&version=1.0.0&docN
summary&docLocation="

Remove an API Document

Description Remove an API document.

URI https:// api.cloud.wso2.com / publisher/site/blocks/documentation/ajax/docs.jag

URI action=removeDocumentation&provider=xxx&apiName=xxx&version=xxx&docName=xxx&docType=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/publisher/site/blocks/documentation/ajax/docs.jag -d


'action=removeDocumentation&provider=admin&apiName=API1&version=1.0.0&docName=doc1&docType=How
To'

Get all Throttling Tiers

Description Get the throttling tiers that can be applied to APIs

URI https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag?

URI action=getTiers
Parameters

HTTP GET
Methods

Example curl -b cookies https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag?action=


getTiers

Copyright © WSO2 Inc. 2014-2017 242


WSO2 API Cloud

Check if API Exists

Description Check if an API by a given name exists in the API Publisher

URI https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag

URI action=isAPINameExist&apiName=<name of the API>


Parameters

HTTP GET
Methods

Example curl -b cookies " https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag?action=is


APINameExist&apiName=PhoneVerification"

Validate Roles

Description Check if the user logged in user is any one in a given list of users

URI https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag

URI action=validateRoles&roles=<list of roles>


Parameters

HTTP GET
Methods

Example curl -b cookies " https:// api.cloud.wso2.com /publisher/site/blocks/item-add/ajax/add.jag?action=v


alidateRoles&roles=admin"

Get List of API Creators

Description Get the list of all the API creators.

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-usage-user/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload action=getAPIUsageByUser&currentLocation=/publisher/site/pages/all-statistics.jag&fromDate=2014-05-10 00:0

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getAPIUsageByUse

Copyright © WSO2 Inc. 2014-2017 243


WSO2 API Cloud

Sample < H T
Response <
< D a t e : M o n ,
<
<
<
<
<
<
< X - X S S -
<
* C o n n e c t i o n # 0
{"error" : false, "usage" : [{"apiName" : "buzzwordapi", "version" : "1.0.0", "userID" : " sabra.wso2.com@sabraorg

Get Subscriber Count

Description Get the number of subscribers.

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-subscriptions/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload a c t i o n : g e t S u b s c r i b e r C o u n t B y A P I s
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
apiFilter:allAPIs

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getSubscriberCoun

Sample < H T
Response <
< D a t e : M o n ,
<
<
<
<
<
<
< X - X S S -
<
* C o n n e c t i o n # 0
{"error" : false, "usage" : [{"apiName" : ["buzzwordapi", "1.0.0", "sabra.wso2.com-AT-sabraorg"], "count" : 2}, {"ap

Get API Usage By Resource Path

Description Get the API usage based on the resource path.

Copyright © WSO2 Inc. 2014-2017 244


WSO2 API Cloud

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-usage-resource-path/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload a c t i o n : g e t A P I U s a g e B y R e s o u r c e P a t h
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
f r o m D a t e : 2 0 1 4 - 0 5 - 1 0
t o D a t e : 2 0 1 6 - 1 2 - 1 6
apiFilter:allAPIs

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getAPIUsageByRe


ce-path/ajax/stats.jag'

Sample < H T
Response <
< D a t e : M o n ,
<
<
<
<
<
<
< X - X S S -
<
{"error" : false, "usage" : [{"apiName" : "buzzwordapi", "version" : "1.0.0", "context" : "/t/sabraorg/buzzwordser
"2016-04-25 04:54", "resourcePath" : "/buzzwordservice/1.0.0/all"}, {"apiName" : "buzzwordapi", "version
"/t/sabraorg/buzzwordservice/1.0.0", "method" : "GET", "count" : 3, "time" : "2016-04-25 04:44", "resourcePath
05:29", "resourcePath" : "/buzzwordservicenew/1.0.0/mostPopular"}]}

Get API Usage By Destination

Description Get the API usage based on the destination

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-usage-destination/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Copyright © WSO2 Inc. 2014-2017 245


WSO2 API Cloud

Payload a c t i o n : g e t A P I U s a g e B y D e s t i n a t i o n
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
f r o m D a t e : 2 0 1 4 - 0 5 - 1 0
t o D a t e : 2 0 1 6 - 1 2 - 1 6
apiFilter:allAPIs

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getAPIUsageByDe


n/ajax/stats.jag'

Sample < H T
Response <
< D a t e : F r i ,
<
<
<
<
<
<
< X - X S S -
<
* C u r l _ h t t p _ d o n e :
* C o n n e c t i o n # 0
{"error" : false, "usage" : [{"apiName" : "Cedum", "version" : "1.0.0", "context" : "/t/anuruddha/demo/1.0.0", "desti

Get API Usage by Provider

Description Get API Usage by Provider.

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-usage/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload a c t i o n : g e t P r o v i d e r A P I U s a g e
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
f r o m D a t e : 2 0 1 4 - 0 5 - 1 0
t o D a t e : 2 0 1 6 - 1 2 - 1 6
apiFilter:allAPIs

Example curl -v -b cookies


tion=getProviderAPIUsage&currentLocation=%2Fpublisher%2Fsite%2Fpages%2Fall-statistics.jag&fromDate=2

Copyright © WSO2 Inc. 2014-2017 246


WSO2 API Cloud

Sample < H T
Response <
< D a t e : F r i ,
<
<
<
<
<
<
< X - X S S -
<
* C u r l _ h t t p _ d o n e :
* C o n n e c t i o n # 0
{"error" : false, "usage" : [{"apiName" : "[\"Cedum\",\"1.0.0\",\"anuruddhal.wso2.com-AT-anuruddha\"]", "count" :

Get API and Application Throttling Data

Description Get the throttling related data related to the APIs and applications.

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/api-throttledcounts/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload a c t i o n : g e t T h r o t t l e D a t a O f A P I A n d A p p l i c a t i o n
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
f r o m D a t e : 2 0 1 4 - 0 5 - 1 0
t o D a t e : 2 0 1 6 - 1 2 - 1 6
a p i F i l t e r : a l l A P I s
a p i N a m e :
appName:

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getThrottleDataOfA


her/site/blocks/stats/api-throttledcounts/ajax/stats.jag'

Copyright © WSO2 Inc. 2014-2017 247


WSO2 API Cloud

Sample < H T
Response <
< D a t e : F r i ,
<
<
<
<
<
<
< X - X S S -
<
JSESSIONID=AA2ADAFAD614FDDCE276E1E63EA836BBEBF098FA685A4FE6B8BB9110FC1E4B8688C618
P a t h = / p u b l i s h e r / ;
<
* C u r l _ h t t p _ d o n e :
* C o n n e c t i o n # 0
{ " e r r o r " : f a l s e } l o c a l h
JSESSIONID=AA2ADAFAD614FDDCE276E1E63EA836BBEBF098FA685A4FE6B8BB9110FC1E4B8688C618
Secure; HttpOnly' -H "Content-type: application/x-www-form-urlencoded" -d 'action=getThrottleDataOfAPIAndA
b l o c k s / s t a t s / a p i - t h r o t t l e d c o u n t s / a j a x / s t a t s . j a g '
{"error" : false, "usage" : {"result" : [{"apiName" : "Cedum", "apiPublisher" : "__all_providers__@anuruddha", "s
"day", "timeUnitMili" : 86400000}}

Get API Response Fault Count

Description Get the response fault count of APIs.

URI https://api.cloud.wso2.com/publisher/site/blocks/stats/faulty-invocations/ajax/stats.jag

Request " C o n t e n t - T y p e "


Headers “ C o o k i e ”
“JSESSIONID=29FCD6CF81BED3701B2F0FD00A7D14B6574F6BF4AF4F4A4D3E6DA7CE1DB8AC82882E3C
Path=/publisher/; Secure; HttpOnly”

HTTP POST
Methods

Payload a c t i o n : g e t T h r o t t l e D a t a O f A P I A n d A p p l i c a t i o n
c u r r e n t L o c a t i o n : / p u b l i s h e r / s i t e / p a g e s / a l l - s t a t i s t i c s . j
f r o m D a t e : 2 0 1 4 - 0 5 - 1 0
t o D a t e : 2 0 1 6 - 1 2 - 1 6
apiFilter:allAPIs

Example curl -v -b cookies -XPOST -H "Content-type: application/x-www-form-urlencoded" -d 'action=getAPIResponseFa


ax/stats.jag '

Copyright © WSO2 Inc. 2014-2017 248


WSO2 API Cloud

Sample < H T
Response <
< D a t e : F r i ,
<
<
<
<
<
<
< X - X S S -
<
* C u r l _ h t t p _ d o n e :
* C o n n e c t i o n # 0
{"error" : false, "usage" : [{"apiName" : "Cedum", "version" : "1.0.0", "context" : "/t/anuruddha/demo/1.0.0", "faultP

Store APIs

Note that the APIs on this page are deprecated. Click https://docs.wso2.com/display/AM200/apidocs/store f
or the recommended list of Store APIs.

The API Store functionality can be programmatically invoked using the following APIs:

[ Login ] [ Logout ] [ User Signup ] [ Search APIs ] [ Get all Paginated Published APIs ] [ Get Published APIs by
Application ] [ Add an Application ] [ Update an Application ] [ Get Applications ] [ Remove an Application ] [ Generate
an Application Key ] [ Add a Subscription ] [ List Subscriptions ] [ List Subscriptions by Application ] [ Remove a
Subscription ] [ Delete an OAuth Application ] [ Provision an Out-of-Band OAuth Client ] [ Clean Partially Created
Keys ] [ Get all Documentation ] [ Get the Contents of a File Document ] [ Add an API Comment ] [ Get all Endpoint
URLs ] [ Get all Available Tiers ]

Note: When you access any API other than the login and logout, first invoke the login API to ensure that user is authenticated. When
the login API is invoked, the system stores the generated session cookie in a file, which is used in the next API invocation/s.

Login

Description Log in to API Store.

URI https://api.cloud.wso2.com/store/site/blocks/user/login/ajax/login.jag

URI action=login&username=xxx&password=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -c cookies https://api.cloud.wso2.com/store/site/blocks/user/login/ajax/login.jag -d


'action=login&username=user1&password=xxx'

The <user name> should be email@organization_key. For example, if the e-mail is jhon@gmail.co
m, the <user name> should be jhon@gmail.com@organization_key. You can find the
organization_key on the Manage page of the cloud.

Logout

Copyright © WSO2 Inc. 2014-2017 249


WSO2 API Cloud

Description Log out from API Store.

URI https://api.cloud.wso2.com/store/site/blocks/user/login/ajax/login.jag

URI ?action=logout
Parameters

HTTP Methods GET

Example curl -b cookies https://api.cloud.wso2.com/store/site/blocks/user/login/ajax/login.jag?action=log


out

User Signup

Description Add a new API Consumer.

URI https://api.cloud.wso2.com/store/site/blocks/user/sign-up/ajax/user-add.jag

URI action=addUser&username=xxx&password=xxx&allFieldsValues=firstname|lastname|email
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/user/sign-up/ajax/user-add.jag


-d 'action=addUser&username=user2&password=xxx&allFieldsValues=firstname|lastname|email'

Search APIs

Description Search for APIs using a given query.

URI https://api.cloud.wso2.com/store/site/blocks/search/api-search/ajax/search.jag

URI action=searchAPIs&query=<query>&start=<number>&end=<number>
Parameters
The start and end parameters determine the range of APIs you want to retrieve. For example, if
start=1 and end=3, the first 3 APIs that appear in the search results will be returned. Note that both
0 and 1 represent the first API in the search results, so start=0 and start=1 both means the same.

HTTP POST
Methods

Example curl -X POST -b cookies "https://api.cloud.wso2.com/store/site/blocks/search/api-search/ajax/searc


h.jag" -d "action=searchAPIs&query=test&start=0&end=3"

Get all Paginated Published APIs

Description Get a list of all published APIs in paginated form so that


browsing is easier.

URI https://api.cloud.wso2.com /store/site/blocks/api/listing/


ajax/list.jag

URI Parameters action=getAllPaginatedPublishedAPIs, tenant, start,


end

Copyright © WSO2 Inc. 2014-2017 250


WSO2 API Cloud

HTTP Methods GET

Example curl -b cookies https://api.cloud.wso2.com/store/site/blo


cks/api/listing/ajax/list.jag?action=getAllPaginatedPubli
shedAPIs&tenant=carbon.super&start =0&end=2

Please note that the getAllPublishedAPIs API is deprecated. You can get the same functionality from g
etAllPaginatedPublishedAPIs.

Get Published APIs by Application

Description Get a list of published APIs filtered by the subscribed


Application. Login API needs be called prior to calling
this API.

URI https://api.cloud.wso2.com/store/site/blocks/subscriptio
n/subscription-list/ajax/subscription-list.jag

URI Parameters action=getSubscriptionByApplication&app=App1

HTTP Methods GET

Example curl -b cookies https://api.cloud.wso2.com/store/site/blo


cks/subscription/subscription-list/ajax/subscription-list.j
ag?action=getSubscriptionByApplication&app=App1

Add an Application

Description Add a new application.

URI https://api.cloud.wso2.com/store/site/blocks/application/application-add/ajax/application-add.jag

URI action=addApplication&application=xxx&tier=xxx&description=xxx&callbackUrl
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/application/application-add/aja


x/application-add.jag -d
'action=addApplication&application=app1&tier=Gold&description=&callbackUrl='

Update an Application

Description Update an existing application.

URI https://api.cloud.wso2.com/store/site/blocks/application/application-update/ajax/application-update.jag

URI action=updateApplication&applicationOld=xxx&applicationNew=xxx&callbackUrlNew=xxx&descriptionNew=xxx&
Parameters

HTTP POST
Methods

Copyright © WSO2 Inc. 2014-2017 251


WSO2 API Cloud

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/application/application-update/ajax/applicat


ate.jag -d
'action=updateApplication&applicationOld=app1&applicationNew=app2&tier=Gold&descriptionNew=&callbackUr

Get Applications

Description Get list of applications.

URI https://api.cloud.wso2.com/store/site/blocks/application/application-list/ajax/application-list.jag

URI ?action=getApplications
Parameters

HTTP GET
Methods

Example curl -b cookies https://api.cloud.wso2.com/store/site/blocks/application/application-list/ajax/applicati


on-list.jag?action=getApplications

Remove an Application

Description Remove an existing application.

URI https://api.cloud.wso2.com/store/site/blocks/application/application-remove/ajax/application-remov
e.jag

URI action=removeApplication&application=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/application/application-remov


e/ajax/application-remove.jag -d 'action=removeApplication&application=app2'

Generate an Application Key

Description Generate the key and secret values for a new application.

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag

URI action=generateApplicationKey&application=<app_name>&keytype=<PRODUCTION|SANDBOX>&
Parameters callbackUrl=<URL>&authorizedDomains=<The domains from which requests are allowed to the
APIs>&validityTime=<time duration in seconds>&tokenScope

tokenScope is given in the request when your API has Auth scopes defined. See OAuth scopes.

HTTP POST
Methods

Copyright © WSO2 Inc. 2014-2017 252


WSO2 API Cloud

Examples
1. curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscriptio
n-add/ajax/subscription-add.jag -d 'action=generateApplicationKey&application=NewApp1&k
eytype=PRODUCTION&callbackUrl=&authorizedDomains=ALL&validityTime=360000'
2. curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscriptio
n-add/ajax/subscription-add.jag -d 'action=generateApplicationKey&application=NewApp1&k
eytype=SANDBOX&callbackUrl=&authorizedDomains=ALL&validityTime=360000&tokenSc
ope=scope1'

Add a Subscription

Description Add a new API subscription.

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag

URI action=addSubscription&name=xxx&version=xxx&provider=xxx&tier=xxx&applicationId=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-add/


ajax/subscription-add.jag -d
'action=addSubscription&name=API1&version=1.0.0&provider=user1&tier=gold&applicationId=1'

List Subscriptions

Description List all API subscriptions.

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag

URI action=getAllSubscriptions
Parameters

HTTP GET
Methods

Example curl -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-list/ajax/subsc


ription-list.jag?action=getAllSubscriptions

List Subscriptions by Application

Description List all API subscriptions of a given application.

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-list/ajax/subscription-list.jag

URI action=getSubscriptionByApplication&app=<application_name>
Parameters

HTTP GET
Methods

Example curl -b cookies 'https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-list/ajax/subsc


ription-list.jag?action=getSubscriptionByApplication&app=DefaultApplication'

Copyright © WSO2 Inc. 2014-2017 253


WSO2 API Cloud

Remove a Subscription

Description Remove an API subscription

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-remove/ajax/subscription-remove.ja
g

URI action=removeSubscription&name=xxx&version=xxx&provider=xxx&applicationId=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-remove/aja


x/subscription-remove.jag -d
'action=removeSubscription&name=API1&version=1.0.0&provider=user1&applicationId=1'

Delete an OAuth Application

Description Deletes an OAuth application in a third-party


Authorization Server. If you delete it through the API
Store UI, only the mapping that is maintained in the API
Cloud will be deleted.

URI https://api.cloud.wso2.com/store/site/blocks/subscriptio
n/subscription-add/ajax/subscription-add.jag

URI Parameters action=deleteAuthApplication&consumerKey=<applic


ation_key>

HTTP Methods POST

Example curl -k -X POST -b cookies https://api.cloud.wso2.com/


store/site/blocks/subscription/subscription-add/ajax/sub
scription-add.jag -d
'action=deleteAuthApplication&consumerKey=4lHddsx
CtpFa2zJE1EbBpJy_NIQa'

Provision an Out-of-Band OAuth Client

Description Provisions an OAuth client that was created out-of-band.

URI https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag

URI action=mapExistingOauthClient&application=semi&keytype=PRODUCTION/SANDBOX&callback
Parameters Url=<URL>&authorizedDomains=<The domains from which requests are allowed to the APIs> &vali
dityTime=<time duration in seconds>&client_id=<client ID>

HTTP POST
Methods

Copyright © WSO2 Inc. 2014-2017 254


WSO2 API Cloud

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/subscription/subscription-add/


ajax/subscription-add.jag -d 'action=mapExistingOauthClient&application=semi&keytype=PRODUC
TION&callbackUrl=google.com&authorizedDomains=ALL&validityTime=3600&client_id=mPbgvinvp
Ek1QcSrw962TLICriUa&jsonParams={"username":"admin","key_type":"PRODUCTION","client_sec
ret":"ynEI1ugq1_RCTJ9bM8jtD9RCsdoa","validityPeriod":3600,"client_id":"mPbgvinvpEk1QcSrw96
2TLICriUa"}'

Clean Partially Created Keys

Description Cleans any partially created keys from the API Cloud
database, before adding a new subscription. Partially
created keys can remain in the API Cloud databases
when an OAuth application of a third-party
authorization server gets deleted using the API Store
UI. It only deletes the mapping that is maintained in the
API Cloud side.

URI https://api.cloud.wso2.com/store/site/blocks/subscriptio
n/subscription-add/ajax/subscription-add.jag

URI Parameters action=cleanUpApplicationRegistration&applicationN


ame=xxx&keyType=PRODUCTION/SANDBOX'

HTTP Methods POST

Example curl -X POST -b cookies https://api.cloud.wso2.com/sto


re/site/blocks/subscription/subscription-add/ajax/subscr
iption-add.jag -d
'action=cleanUpApplicationRegistration&applicationNa
me=DefaultApplication&keyType=PRODUCTION'

Get all Documentation

Description Get all documents create for a given API

URI https://api.cloud.wso2.com/store/site/blocks/api/listing/ajax/list.jag

URI action=getAllDocumentationOfApi&name=<API Name>&version=x.x.x&provider=<Name of the API provider>"


Parameters

HTTP GET
Methods

Example curl -b cookies "https://api.cloud.wso2.com/store/site/blocks/api/listing/ajax/list.jag?action=getAllDocumentationO


Verification&version=1.0.0&provider=admin"

Get the Contents of a File Document

Description Get the contents of a file that is attached to API


documentation of type 'File'

URI https://api.cloud.wso2.com/store/site/blocks/api/docum
entation/view/ajax/file-docs.jag

Copyright © WSO2 Inc. 2014-2017 255


WSO2 API Cloud

URI Parameters action=getFileDocumentByFilePath&filePath=<Get the


file path using getAllDocumentationOfApi>

HTTP Methods GET

Example curl -b cookies "https://api.cloud.wso2.com/store/site/bl


ocks/api/documentation/view/ajax/file-docs.jag?action=
getFileDocumentByFilePath&filePath=/registry/resourc
e/_system/governance/apimgt/applicationdata/provider/
admin/host/1.0.0/documentation/files/test.txt''

Add an API Comment

Description Add a comment to an API.

URI https://api.cloud.wso2.com/store/site/blocks/comment/comment-add/ajax/comment-add.jag

URI action=addComment&name=xxx&version=xxx&provider=xxx&comment=xxx
Parameters

HTTP POST
Methods

Example curl -X POST -b cookies https://api.cloud.wso2.com/store/site/blocks/comment/comment-add/ajax/c


o m m e n t - a d d . j a g - d
'action=addComment&name=CalculatorAPI&version=1.0&provider=admin&comment=test
comment'

Get all Endpoint URLs

Description Get all the endpoint URLs of the API Gateway


environments configured for an API.

URI https://api.cloud.wso2.com/store/site/blocks/api/api-info
/ajax/api-info.jag

URI Parameters action=getAPIEndpointURLs&name=xxx&version=x.x.x


&provider=xxx

HTTP Methods POST

Example curl -X POST -b cookies https://api.cloud.wso2.com/sto


re/site/blocks/api/api-info/ajax/api-info.jag -d
'action=getAPIEndpointURLs&name=CalculatorAPI&ve
rsion=1.0&provider=admin'

Get all Available Tiers

Description Get all the tiers available in the deployment.

Copyright © WSO2 Inc. 2014-2017 256


WSO2 API Cloud

URI https://api.cloud.wso2.com/store/site/blocks/item-add/ajax/add.jag

URI action=getTiers
Parameters

HTTP Methods GET

Example curl -b cookies https://api.cloud.wso2.com/store/site/blocks/item-add/ajax/add.jag?action=getTi


ers

Token API
Users need access tokens to invoke APIs subscribed under an application. Access tokens are passed in the HTTP
header when invoking APIs. The API Cloud provides a Token API that you can use to generate and renew user and
application access tokens. The response of the Token API is a JSON message. You extract the token from JSON
and pass it with an HTTP Authorization header to access the API.

The following topic explains how to generate/renew access tokens using the Token API and authorize them. WSO2
API Cloud supports the most common authorization grant types. You can also define additional types.

Authorization Code Grant


Refresh Token Grant
Password Grant
SAML Extension Grant
Client Credentials Grant

Authorization Code Grant

Instead of requesting authorization directly from the resource owner (resource owner's credentials), in this grant
type, the client directs the resource owner to an authorization server. The authorization server works as
an intermediary between the client and resource owner to issues an authorization code, authenticate the resource
owner and obtain authorization. As this is a redirection-based flow, the client must be capable of interacting with the
resource owner's user-agent (typically a Web browser) and receiving incoming requests (via redirection) from the
authorization server.

The client initiates the flow by directing the resource owner's user-agent to the authorization endpoint (you can use
the /authorize endpoint for the authorization code grant type of OAuth 2.0). It includes the client identifier,
response_type, requested scope, and a redirection URI to which the authorization server sends the user-agent back
after granting access. The authorization server authenticates the resource owner (via the user-agent) and
establishes whether the resource owner granted or denied the client's access request. Assuming the resource
owner grants access, the authorization server then redirects the user-agent back to the client using the redirection
URI provided earlier. The redirection URI includes an authorization code.

The client then requests an access token from the authorization server's /token endpoint by including the
authorization code received in the previous step. When making the request, the client authenticates with the
authorization server. It then includes the redirection URI used to obtain the authorization code for verification. The
authorization server authenticates the client, validates the authorization code, and ensures that the redirection URI
matches the URI used to redirect the client from the /authorize endpoint in the previous response. If valid, the
authorization server responds back with an access token and, optionally, a refresh token.

Invoking the Token API to generate tokens

The Authorization API URL is https://api.cloud.wso2.com:8243/authorize.

Copyright © WSO2 Inc. 2014-2017 257


WSO2 API Cloud

query component: response_type=code&client_id=<consumer_key>&scope=PRODUCTION&red


irect_uri=<application_callback_url>
headers: Content-Type: application/x-www-form-urlencoded

For example, the client directs the user-agent to make the following HTTP request using TLS.

GET
/authorize?response_type=code&client_id=wU62DjlyDBnq87GlBwplfqvmAbAa&scope
=PRODUCTION&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
HTTP/1.1
Host: server.example.com
Content-Type:
application/x-www-form-urlencoded

The authorization server redirects the user-agent by sending the following HTTP response:

HTTP/1.1 302 Found


Location:
https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA

Now the client makes the following HTTP request using TLS to the /token endpoint.

POST /token HTTP/1.1


Host: server.example.com
Authorization: Basic
SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVz
hh
Content-Type:
application/x-www-form-urlencoded
grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=htt
ps%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb

The /token endpoint responds in the same way like in password grant type.

<Authenticators>
<Authenticator name="BasicAuthenticator" disabled="false" factor="1">
<Status value="10" loginPage="/authenticationendpoint/login.do" />
</Authenticator>
</Authenticators>

Refresh Token Grant

After an access token is generated, sometimes you might have to refresh or renew the old token due to expiration or
security concerns. You use the refresh token grant when a new access token is needed. With this grant type, the
refresh token acts as credentials that are issued to the client by the authorization server. Issuing a refresh token is

Copyright © WSO2 Inc. 2014-2017 258


WSO2 API Cloud

optional. If the authorization server issues a refresh token, it is included when issuing an access token. Refresh
tokens are issued for all other grant types other than the implicit grant as recommended by the OAuth 2.0
specification.

Tip: Be sure to keep the refresh token private, similar to the access token as this token issues access
tokens without user interactions.

To use this grant type, you need a refresh token, using which you can get a new access token and a refresh token.
This can be done by issuing a REST call to the Token API through a REST client like cURL, with the following
parameters:

The Token API URL is https://gateway.api.cloud.wso2.com/token.


payload - "grant_type=refresh_token&refresh_token=<retoken>&scope=PRODUCTION".
Replace the <retoken> value with the refresh token that you have.
headers - Authorization :Basic <base64 encoded string of
consumer-key:consumer-secret>, Content-Type: application/x-www-form-urlencoded.
Replace <base64 encoded string of consumer-key:consumer-secret> as appropriate.

For example, the following cURL command can be used to access the Token API and grant a refresh token.

curl -k -d
"grant_type=refresh_token&refresh_token=<retoken>&scope=PRODUCTION" -H
"Authorization: Basic
SVpzSWk2SERiQjVlOFZLZFpBblVpX2ZaM2Y4YTpHbTBiSjZvV1Y4ZkM1T1FMTGxDNmpzbEFDVz
hh, Content-Type: application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com/token

When you use the refresh grant to get a new access token, the refresh token is renewed by default. The new refresh
token has a new expiry time and the previous refresh token becomes inactive.

Revoking access tokens

After issuing an access token, a user or an admin can revoke it in case of theft or a security violation. You can do
this by calling the Revoke API using a REST Client. The Revoke API's endpoint URL is https://gateway.api.c
loud.wso2.com/revoke. The parameters required to invoke this API are as follows:

The token to be revoked


Consumer key and consumer secret key. Must be encoded using Base64 algorithm

For example:

curl -k -d "token=<ACCESS_TOKEN_TO_BE_REVOKED>" -H "Authorization: Basic


Base64Encoded(Consumer key:consumer secret)"
https://gateway.api.cloud.wso2.com/revoke

Even after revoking a token, it might still be available in the API Gateway cache to consumers until the cache expires in approximately
15 minutes.

Password Grant

Copyright © WSO2 Inc. 2014-2017 259


WSO2 API Cloud

You can obtain an access token by providing the resource owner's username and password as an authorization
grant. It requires the base64 encoded string of the consumer-key:consumer-secret combination. You need to
meet the following prerequisites before using the Token API to generate a token.

Prerequisites

A valid user account in the API Store.


A valid consumer key and consumer secret pair. Initially, these keys must be generated through the API
Store by clicking the Generate link on My Subscriptions page.

Invoking the Token API to generate tokens

1. Combine the consumer key and consumer secret keys in the format consumer-key:consumer-secret and
encode the combined string using base64. Encoding to base64 can be done using the URL:http://base64enc
ode.org.
Here's an example consumer key and secret combination : wU62DjlyDBnq87GlBwplfqvmAbAa:ksdSdoe
fDDP7wpaElfqvmjDue.
2. Access the Token API by using a REST client such as cURL, with the following parameters.
The token API URL is https://api.cloud.wso2.com:8243/token.
payload - "grant_type=password&username=<username>&password=<password>&scope=<
scope>". Replace the <username> and <password> values as appropriate.

Tip: <scope> is optional.

You define scopes for your API's resources so that the resource can only be accessed through
a token that has been issued for at least the scope belonging to the resource. For example, if a
resource has a scope named 'update' and if the token is issued for the scopes 'read' and
'update', then the token is allowed to access the resource. If the token is issued for 'read' only,
the request bearing the particular token will be blocked.

headers - Authorization: Basic <base64 encoded string>, Content-Type:


application/x-www-form-urlencoded. Replace the <base64 encoded string> as
appropriate.

For example, use the following cURL command to access the Token API. It generates two tokens as an
access token and a refresh token. You can use the refresh token at the time a token is renewed.

curl -k -d
"grant_type=password&username=<username>&password=<password>" -H
"Authorization: Basic <base64 encoded (consumer key:consumer secret)>"
-H "Content-Type: application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com/token

User access tokens have a fixed expiration time, which is set to 60 minutes by default. When a user
access token expires, the user can try regenerating the token as explained in the Renew user tokens sect
ion.

Instead of using the Token API, you can generate access tokens from the API Store's UI.

SAML Extension Grant

Copyright © WSO2 Inc. 2014-2017 260


WSO2 API Cloud

SAML 2.0 is an XML-based protocol. It uses security tokens containing assertions to pass information about an
end-user between a SAML authority and a SAML consumer. A SAML authority is an identity provider (IDP) and a
SAML consumer is a service provider (SP).

Enterprise applications that have SAML2 based SSO infrastructures sometimes need to consume OAuth-protected
resources through APIs. However, these apps prefer to use the existing trust relationship with the IDP, even if the
OAuth authorization server is entirely different from the IDP. The API Cloud leverages this trust relationship by exch
anging the SAML2.0 token to an OAuth token with the authorization server. It acts as the OAuth authorization
server.

The diagram below depicts this scenario. It uses WSO2 Identity Server (version 4.5.0 onwards) as the IDP.

The scenarios of the above diagram are explained below:

Scenario [1]: User initiates a login call to an enterprise application

Scenario [2]:

As the application is a SAML SP, it redirects the user to the SAML2.0 IDP to log in.
The user provides credentials at the IDP and is redirected back to the SP with a SAML2.0 token signed by
the IDP.
The SP verifies the token and logs the user to the application.
The SAML 2.0 token is stored in the user's session by the SP.

Scenario [3]:

The enterprise application (SP) wants to access an OAuth2 protected API resource through WSO2 API
Cloud.
The application makes a request to the API Cloud to exchange the SAML2 bearer token for an OAuth2.0
access token.
The API Cloud validates the assertion and returns the access token.

Scenario [4]: User does API invocations through the API Cloud by setting it as an Authorization header with the
returned OAuth2 access token.

Copyright © WSO2 Inc. 2014-2017 261


WSO2 API Cloud

Let's configure the token exchange.

Configuring the token exchange

Before you begin, make sure you have the following:

A valid user account in the API Store.


A valid consumer key and consumer secret. Initially, these keys must be generated through the API
Store by clicking the Generate link on My Subscriptions page.

We use WSO2 Identity Server 5.0.0 as the IDP to get a SAML token and the API Cloud as the OAuth server.

1. Log in to the API Manager's Management Console using the URL https://gatewaymgt.api.cloud.wso2.com/car
bon. Use the same credentials that you used to log in to WSO2 Cloud.

2. Select Add under Identity Providers menu in the Main menu in the left-hand side of the screen.

3. Provide the following values to configure the IDP:


Under Basic Information
Identity Provider Name: Enter a unique name for IDP
Identity Provider Public Certificate: The certificate used to sign the SAML assertion. Export
the public certificate of WSO2 IS and import it here.

Alternatively, you can create a self-signed certificate and then export it as a .cer file using the
following commands:

keytool -genkey -alias wookie -keyalg RSA -keystore


wookieKeystore.jks -keysize 4096
keytool -v -export -file keystore1.cer -keystore
keystore1.jks -alias keystore1

Alias: Give the name of the alias if the Identity Provider identifies this token endpoint by an
alias. E.g., https://keymanager.api.cloud.wso2.com/oauth2/token.
Under Federated Authenticators -> SAML2 Web SSO Configuration

Enable SAML2 Web SSO: true

Identity Provider Entity Id: The SAML2 issuer name specified when generating the assertion
token, which contains the unique identifier of the IDP. You give this name when configuring
the SP.

Service Provider Entity Id: Issuer name given when configuring the SP
SSO URL: Enter the IDP's SAML2 Web SSO URL value. E.g., https://localhost:9444/samlsso/ if
you have offset the default port, which is 9443.
4. Make sure you have a service provider that issues tokens for them.

Next, let's see how to get a signed SAML2 token (encoded assertion value) when authenticating against a

Copyright © WSO2 Inc. 2014-2017 262


4. WSO2 API Cloud

SAML2 IDP. With the authentication request, you pass attributes such as the SAML2 issuer name, token
endpoint and the restricted audience. In this guide, we use a command-line client program to create the
SAML2 assertion.
5. Download the SAML2AssertionCreator.zip file from here. It contains the SAML token generation client
JAR that you use in the next step.
6. Get the SAML token using the SAML2AssertionCreator.jar as shown in the following command:

java -jar SAML2AssertionCreator.jar <Identity_Provider_Entity_Id>


<user_name> <recipient> <requested_audience>
<Identity_Provider_JKS_file> <Identity_Provider_JKS_password>
<Identity_Provider_certificate_alias> <private_key_password>

Here's an example where TestSP is the name of the issuer.

java -jar SAML2AssertionCreator.jar TestSP user1


https://keymanager.api.cloud.wso2.com/oauth2/token
https://keymanager.api.cloud.wso2.com/oauth2/token
home/ubuntu/wso2is-5.0.0/repository/resources/security/wso2carbon.jks
wso2carbon wso2carbon wso2carbon

7. Get the OAuth Access token. An example command is given below.

curl -k -d
"grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=<
ASSERTION_PROVIDED_BY_CLIENT>&scope=PRODUCTION" -H "Authorization:
Basic <Base63 encoded consumer key:consumer secret>, Content-Type:
application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com:8243/token?tenantDomain=<your_tena
nt_domain>

Invoking the Token API to generate tokens

Follow the steps below to invoke the token API to generate access tokens from SAML2 assertions.

1. Combine the consumer key and consumer secret keys as consumer-key:consumer-secret. Encode the
combined string using base64 ( http://base64encode.org). Here's an example consumer key and secret
combination: wU62DjlyDBnq87GlBwplfqvmAbAa:ksdSdoefDDP7wpaElfqvmjDue.
2. Access the token API using a REST client such as the WSO2 REST Client or Curl. The parameters are
explained below:
Assuming that both the client and the API Gateway run on the same server, the Token API URL is http
s://localhost:8243/token.
Create a SAML2 Assertion.
You can use the command line client program from here. Extract the ZIP file, change directory into the
extracted folder and execute the following command in the command line. You will get
SAML2 Assertion XML String and base64-URL Encoded Assertion XML String. Use base64-URL
Encoded Assertion XML String as SAML2_Encoded Assertion_Token.

Copyright © WSO2 Inc. 2014-2017 263


WSO2 API Cloud

java -jar SAML2AssertionCreator.jar <Identity_Provider_Entity_Id>


admin https://localhost:9443/oauth2/token
https://localhost:9443/oauth2/token <Identity_Provider_JKS_file>
<Identity_Provider_JKS_password>
<Identity_Provider_certificate_alias>

The arguments are as follows:

The saml:Issuer (a unique identifier of the identity provider) value


The saml:Subject -> saml:NameId value
The value of saml:Subject -> saml:SubjectConfirmation ->
saml:SubjectConfirmationData.Recipient
The fourth argument can take multiple values separated by commas. They are added to the
saml:AudienceRestriction element of the token. Each value is added as a saml:Audience
element within saml:AudienceRestriction.
Pointer to the Java Key Store (JKS) file to be used for credentials
The JKS password
The alias of the public certificate
The password of the private key that is used for signing
payload - "grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=
<SAML2_Encoded_Assertion_Token> &scope=PRODUCTION". Replace the <SAML2_Encoded_
Assertion_Token> value as appropriate.

headers - Authorization :Basic <base64 encoded consumer-key:consumer-secret>,


Content-Type: application/x-www-form-urlencoded. Replace the <base64 encoded co
nsumer-key:consumer-secret> as appropriate.

For example, the following Curl command is used to access the Token API. It generates an access token and
a refresh token. You can use the refresh token at the time a token is renewed.

curl -k -d
"grant_type=urn:ietf:params:oauth:grant-type:saml2-bearer&assertion=<
Assertion_provided_by_client>&scope=PRODUCTION" -H "Authorization:
Basic <Base64 encoded consumer key:consumer secret>, Content-Type:
application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com:8243/token?tenantDomain=<your_tena
nt_domain>

Client Credentials Grant

The client credentials grant is suitable for machine-to-machine authentication or for clients making requests to an
API that does not require the user’s permission. For example, application developers can use this grant type to
remotely authenticate applications. Only trusted clients must be allowed to use this grant type.

In this grant type, the client requests an access token using only the client credentials to authenticate a request for
an access token. This does not have support for the refresh token grant.

Here are the cURL commands to use the client credentials grant:

Copyright © WSO2 Inc. 2014-2017 264


WSO2 API Cloud

curl -v -X POST -H "Authorization: Basic <base64 encoded client id:client


secret value>" -k -d "grant_type=client_credentials&validity_period=3600"
-H "Content-Type:application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com:443/token

curl -u <client id>:<client secret> -k -d


"grant_type=client_credentials&validity_period=3600" -H
"Content-Type:application/x-www-form-urlencoded"
https://gateway.api.cloud.wso2.com:443/token

You will receive a response similar to the following:

Response
{"token_type":"Bearer","expires_in":3600,"access_token":"ca19a540f54477786
0e44e75f605d927"}

Copyright © WSO2 Inc. 2014-2017 265


WSO2 API Cloud

FAQ

Where is WSO2 API Cloud hosted?


How can I log into the Cloud's advanced Management Console?
The backend Web service does not match the API design that I expect. What should I do?
What type of mediators are supported by the API Cloud?
How can I secure the link between my backend services and the API Cloud?
What properties can I retrieve from an API using a property mediator within a sequence?
How can I download the Public Certificate of the key used to sign the JWT Token sent to the backend in API
Cloud
How long does it take for a change done in API Publisher to appear in the global API Gateways

1. Where is WSO2 API Cloud hosted?

WSO2 API Cloud is hosted in AWS US East datacenter. For compliance or performance reasons, paying
customers can choose alternative locations for their API gateways in API Cloud. These include Canada, US
West, Brazil (São Paulo), EU (Ireland), EU (Frankfurt), Singapore, Tokyo, Sydney, Seoul, Mumbai, and
Beijing.

2. How can I log into the Cloud's advanced Management Console?

In most cases, default user interfaces are sufficient for your administrative tasks. However, there are some
scenarios such as adding new user roles that require use of the advanced Management Console. Such
scenarios are indicated in the corresponding documentation articles.

You can log into the API Gateway's advanced Management Console using the URL https://gatewaymgt.api.cl
oud.wso2.com/carbon.

3. The backend Web service does not match the API design that I expect. What should I do?
You can extend the default message mediation sequence using mediators. The API Cloud comes with a
powerful mediation engine that can transform and orchestrate API calls on the fly. See Change the Default
Mediation Flow of API Requests.
4. What type of mediators are supported by the API Cloud?

See WSO2 Cloud Mediators.

5. How can I secure the link between my backend services and the API Cloud?
See Secure your Backend Services.
6. What properties can I retrieve from an API using a property mediator within a sequence?

Property Description

SYNAPSE_REST_API_VERSION Retrieves the version of the API. E.g., 1.0.0.

REST_SUB_REQUEST_PATH Retrieves the sub request with path and query parameters. E.g.,
"/CheckPhoneNumber?PhoneNumber=1234567&LicenseKey=0".

REST_API_CONTEXT or api.ut.context Retrieves the context of the API in the form /t/tenantDomain/context/v
API. E.g., "/t/tenant/new/1.0.0".

REST_FULL_REQUEST_PATH Retrieves the entire request path. E.g.,


"/t/tenant/new/1.0.0/CheckPhoneNumber?PhoneNumber=1234567&L

SYNAPSE_REST_API_VERSION_STRATEGY :For example, "context".

Copyright © WSO2 Inc. 2014-2017 266


WSO2 API Cloud

TRANSPORT_IN_NAME Retrieves the transport. For example, "https".

SYNAPSE_REST_API Retrieves the name of the API. For example, "admin-AT-tenant.com--


0".

See this tutorial in the WSO2 ESB documentation, to get an idea on how you can use a property mediator
within a sequence to change the default mediation flow of API requests. Also, see Property Mediator of the
ESB documentation.

7. How can I download the Public Certificate of the key used to sign the JWT Token sent to the backend in API
Cloud

Each tenant in WSO2 Cloud has their own private key and it is used to sign the JWT token. Please follow the
below steps to get the public certificate.

1. First go to Cloud's advanced Management Console and Login as your tenant admin
2. List Keystores from home page (Main -> Manage -> Keystores -> List)

3. D o w n l o a d Keystore JKS's public key

8. How long does it take for a change done in API Publisher to appear in the global API Gateways

It takes maximum of 10 minutes for a change done in API Publisher to appear in the global API Gateways.
Reason is, artifact synchronising task is running in every 10 minutes.

Copyright © WSO2 Inc. 2014-2017 267

S-ar putea să vă placă și