SAP API Management User Guide
SAP API Management User Guide
Example Words or characters quoted from the screen. These include field names, screen titles,
pushbuttons labels, menu names, menu paths, and menu options.
Textual cross-references to other documents.
EXAMPLE Technical names of system objects. These include report names, program names,
transaction codes, table names, and key concepts of a programming language when they
are surrounded by body text, for example, SELECT and INCLUDE.
Example Output on the screen. This includes file and directory names and their paths, messages,
names of variables and parameters, source text, and names of installation, upgrade and
database tools.
Example Exact user entry. These are words or characters that you enter in the system exactly as
they appear in the documentation.
<Example> Variable user entry. Angle brackets indicate that you replace these words and characters
with appropriate entries to make entries in the system.
7 References........................................................................................................................... 498
7.1 Analytics Command Reference ....................................................................................................... 498
API...................................................................................................................................... 498
Developers ........................................................................................................................ 500
Apps................................................................................................................................... 502
API Products ..................................................................................................................... 504
API Resources................................................................................................................... 506
SAP Customer may use SAP API Management to process and monitor personal
information in terms of relevant data protection legislation. It is the SAP
Customer’s responsibility to use the SAP API Management only in compliance
with the relevant data protection laws.
An API is a technology architecture that makes it easy for one application to 'consume' capabilities or data from
another application. By defining stable, simplified entry points to application logic and data, APIs enable
developers to easily access and reuse application logic built by other developers. In the case of 'Web APIs', that
logic and data is exposed over the network.
Since applications that consume APIs are sensitive to changes, APIs also imply a 'contract'. The contract provides
some level of assurance that, over time, the API will change in a predictable manner.
SAP API Management enables you to build APIs and if you have APIs already, expose them directly, while adding a
management and visibility layer. If you have HTTP enabled services, such as SOA-based Web services, they can
also be exposed as APIs via SAP API Management.
Companies today want to make their backend services available on the web so that these services can be
consumed by apps running on mobile devices and desktops. A company might want to expose services that
provide product pricing and availability information, sales and ordering services, order tracking services, and any
other services required by client apps.
Companies often expose services as a set of HTTP endpoints. Client app developers then make HTTP requests to
these endpoints. Depending on the endpoint, the service might then return data, formatted as XML or JSON, back
to the client app.
The client apps that consume these services can be implemented as standalone apps for a mobile device or
tablet, as HTML5 apps running in a browser, or as any other type of app that can make a request to an HTTP
endpoint and consume any response data. These apps might be developed and released by the same company
that exposed the services, or by third-party app developers who make use of publicly available services.
The following image shows this type of mJSOnodel:
SAP API Management Edge, which is built on Java, enables you to provide secure access to your services with a
well-defined API that is consistent across all of your services, regardless of service implementation. A consistent
API:
Makes it easy for app developers to consume your services.
Enables you to change the backend service implementation without affecting the public API.
An API proxy is the HTTP endpoint on SAP API Management Edge that developers use to access your backend
services. While it is possible, you typically do not make individual API proxies available. Instead, you group one or
more API proxies into an API product.
An API product is a bundle of API proxies combined with a service plan. That service plan can set access limits on
API proxies, provide security, allow monitoring and analytics, and provide additional features. API products are
also the central mechanism that SAP API Management Edge uses for authorization and access control to your
APIs.
You have a great deal of flexibility when creating API products. For example, multiple API products can share the
same API proxy. The following figure shows three API products. Notice that all products allow access to API proxy
3, but only product A allows access to API proxy 1.
You can set different properties on each API product. For example, you might make available one API product with
a low access limit, such as 1000 requests per day, for a bargain price. You then release another API product that
provides access to the same API proxy, but with a much higher access limit, for a higher price. Or, you might
create a free API product that allows read-only access to your services, and then sell an API product to the same
API proxies that allows read/write access.
When app developers decide that they want to access your services, they must first register their client app with
your API product. Upon registration, an app developer receives an API key that she must then include in every
request to an API proxy included in the API product. That key is authenticated and, if authentication is successful,
the request is allowed to access your backend service.
At any time, you can revoke the key so that the client app no longer has access to your services. Or, you can define
a time limit on a key so that the developer must refresh the key after a specific time.
You decide how to handle registration requests from developers to access your API products. By using SAP API
Management Edge Developer Services, you can automate the registration process; or you can use a manual
process to control access.
• Create one or more API proxies that map publicly available URLs to your backend services.
• Create an API product that bundles your API proxies.
• Deploy your API proxies and API product.
• Let your developers know that the API product is available.
• Once app developers know about the availability of your API product, they:
• Register their client apps with your API product.
• Receive an API key for the API product.
• Make requests to your services through API proxies (which are bundled in the API product) and pass the API
key with each request.
SAP API Management consists of the API Platform, Analytics Services, and Developer Services that together
provide a comprehensive infrastructure for API creation, security, management, and operations, as well as
powerful backend services for developing client apps.
The following figure shows SAP API Management services:
SAP API Management API Platform are all about creating and consuming APIs, whether you're building API
proxies as a service provider or using APIs, SDKs, and other convenience services as an app developer.
Analytics Services
SAP API Management Analytics Services provides powerful tools to see short and long-term usage trends of your
APIs. You can segment your audience by top developers and apps, understand usage by API method to know
where to invest, and create custom reports on business or operational-level information.
As data passes through SAP API Platform, several default types of information are collected including URL, IP,
user ID for API call information, latency, error data, and so on. You can create policies to add other information,
such as headers, query parameters, and portions of a request or response extracted from XML or JSON. This
information is collected asynchronously from the actual request/response flow and therefore has no effect on API
performance.
Developer Services
SAP API Management Developer Services provide the tools to manage the community of app developers using
your services. Developer Services offers the flexibility to work with internal and external developers and formalize
these relationships with financial models.
Developer Services provides the ability to onboard developers and create a developer portal for your publicly
available API products. App developers connect to your portal to access API documentation, forums, and blogs.
Every SAP API Platform customer can create their own developer portal, either in the cloud or on-premise. The
following figure shows the home page of the default developer portal:
SAP API Management, which is built on Java, enables you to provide secure access to your services with a well-
defined API that is consistent across all of your services, regardless of service implementation. A consistent API:
• Makes it easy for app developers to consume your services.
• Enables you to change the backend service implementation without affecting the public API.
• Enables you to take advantage of the analytics, developer portal, and other features built into SAP API
Management.
The following image shows the architecture with SAP API Management handling the requests from client apps to
your backend services:
Rather than having app developers consume your services directly, they access an API proxy created on SAP API
Management. The API proxy functions as a mapping of a publicly available HTTP endpoint to your backend
service. By creating an API proxy you let SAP API Management handle the security and authorization tasks
required to protect your services, as well as to analyze and monitor those services.
Because app developers make HTTP requests to an API proxy, rather than directly to your services, developers do
not need to know anything about the implementation of your services. All the developer needs to know is:
• The URL of the API proxy endpoint.
• Any query parameters, headers, or body parameters passed in a request.
• Any required authentication and authorization credentials.
• The format of the response, including the response data format, such as XML or JSON.
The API proxy isolates the app developer from your backend service. Therefore you are free to change the service
implementation as long as the public API remains consistent. For example, you can change a database
implementation, move your services to a new host, or make any other changes to the service implementation. By
maintaining a consistent frontend API, existing client apps will continue to work regardless of changes on the
backend.
You can use policies on the API proxy to add functionality to a service without having to make any changes to the
backend service. For example, you can add policies to your proxy to perform data transformations and filtering,
Two different audiences make use of SAP API Management and its services:
• Service providers who create API Proxies and API products to expose backend services.
• App developers who consume these API proxies and API products to create apps for mobile and desktop
devices. Client app developers also use API Platform for data persistence and management.
SAP API Platform provides tools to support both types of audiences.
As a service provider, you can use two different development methods to create, configure, and maintain API
proxies and API products:
• Make HTTP requests to the RESTful API to access API Platform services.
• Use the Management UI.
1.8 Organizations
An organization represents the highest level of the App Services data hierarchy. It contains applications (and the
entities and collections they contain) and is associated with one or more administrators. An organization can be
representative of a company, team, or project. It allows multiple applications to be shared within the organization
with other administrators.
Using the API Platform services API, you can create an organization through a form post and get an organization
by UUID or name. In addition, you can activate or reactivate an organization, generate and retrieve an
organization's client credentials, and get an organization's activity feed. You can also create an organization
application through a form post, generate and retrieve credentials for the application, and delete the application.
You can also get the applications in an organization. Additionally, you can add an admin user to an organization,
get the admin users in an organization, and remove an admin user from an organization.
Before you start building APIs with SAP API Management, you should be familiar with the organizational model of
SAP API Platform. This model defines how your APIs, API products, apps, and app developers are all related within
SAP API Platform.
The following image shows the major components of the SAP API Platform organizational model:
Organization will be created when you perform the onboarding activity. See the Installation and Onboarding Guide
for more details. Once the organization is created, you can add users to your organization, create API proxies and
API products, and register developers and apps. You can later add additional organizations as necessary.
Optional: You can make the organization name as part of URL to your API proxies and part of the URL when
making a request to the SAP API Management API. For example, a typical URL used to access an API proxy has
the form:
http://{org-name}-{env}.<host:port>/v1/weather/forecastrss
The following table describes the components of the organizational model in more detail:
Component Description
API Proxy The users in an organization create one or more API proxies. An
API proxy defines a mapping of a publicly available HTTP
endpoint to a backend service. API proxies can also be
configured to include security (such as OAuth), perform
message transformation (such as XML to JSON), limit traffic to
backend services, and perform other valuable operations on the
request, the response, and with service callouts.
SAP API Platform collects data for analytics on API proxies.
API Product The users in an organization create one or more API products,
where an API product is a bundle of API proxies combined with
a service plan. That service plan can set access limits on API
proxies, provide security, allow monitoring and analytics, and
provide additional features.
SAP API Platform collects data for analytics on API products.
App Developers create one or more client apps that consume your
APIs.
Developers must register their apps with your organization. An
App in SAP API Platform is a representation of a developer's
actual app that provides the developer with an API key to pass
in with every request to your APIs.
Because all apps are registered in your organization, you can
use SAP API Platform to monitor and collect analytic
information on the app and on its use of your APIs.
API key/OAuth token Depending on the authorization mechanism you define for your
APIs, the app passes an API key along with every request to
your APIs. If that key is valid, the request is allowed. SAP API
Platform supports different types of authentication, such as a
simple API key, two-legged OAuth, three-legged OAuth, and
others.
As an API provider, you must define a way for developers to
register their apps. It is by registering their app that you return
to the developer the key required to access your APIs.
At the time of app registration, the developer can choose to
access a single API product or multiple API products. The
developer's actual app uses the same key to access all API
products associated with the app (the registered representation
of the developer's app in SAP API Platform).
At any time, you can revoke the key so that the developer's app
no longer has access to your APIs (even though the registered
representation of the developer's app still exists in your
organization). Or, you can define a time limit on a key so that
the developer must refresh the key after a specific time.
Every organization has a unique software development lifecycle (SDLC). It is often necessary to synchronize and
align API proxy deployment with the same processes that you use today for developing, testing, and deploying
other applications.
API Platform provides tools and RESTful APIs that enable you to integrate API proxy deployment and
management into your organization's SDLC. A common usage of the RESTful API is to write scripts or code that
programmatically deploy API proxies, or that migrate API proxies from one environment to another, as part of a
larger automated process that also deploys or migrates other applications. API Platform makes no assumptions
about your SDLC (or anyone else's, for that matter). Rather, it exposes atomic functions that can be coordinated
by your development team to automate and optimize your API development lifecycle.
Every organization on SAP API Management has at least two deployment environments that are available for API
proxies: 'test' and 'prod'. The distinction between the two environments is arbitrary — each environment is simply
identified by a different set of network addresses (URLs). The goal is to provide you with a domain in which you
can build and verify API proxies before the API is exposed to external developers.
You can leverage these environments to synchronize API proxy development processed with your SDLC. Each
environment is defined by a network address, enabling you to segregate traffic between the API proxies that you
are working on, and those that are being accessed by apps at runtime. The network addresses available for each
environment is defined in the set of VirtualHosts available in that environment.
Inbound server SSL is automatically enabled for each environment. The default VirtualHost is pre-defined in each
environment during onboarding. The secure VirtualHost can be created. Default defines an HTTP address, while
secure defines an HTTP/S address, with pre-configured server-side SSL. In an API proxy configuration, you
indicate which VirtualHosts the ProxyEndpoint should listen on. When promoting to prod, you typically disable
HTTP by removing the default VirtualHost from the API proxy configuration. See the Installation and Onboarding
Guide for more information.
Environments also provide segregation of data and resources. You can, for example, set up different caches in
test and prod, which can be accessed only by API proxies executing in that environment. Additionally, API keys
that are issued in the test environment are not valid in the prod environment, and vice-versa.
The UI provides browser-based tooling that lets you perform most of the tasks necessary to create, configure, and
manage API proxies and API products. There are still a few tasks that require you to use the RESTful APIs, though.
The following image shows the Management UI that you can use to create and configure an API proxy:
The UI simplifies many interactions with platform in the context of a browser-based tool. In the UI, you can:
• Create API proxies
• Create API products
• Manage developers, apps, and other parts of your organization
• Configure your test and production environments
• Access the Console
• Access App Services
• Implement JavaScript
An organization administrator can add a new user on SAP API Management Platform. The new user is
automatically added to the administrator's organization.
When the administrator creates new user, you are automatically added to the administrator's organization with
the role determined by the administrator. This is typically the way you will be added as a new user to an existing
organization.
The SAP API Management Platform is a RESTful API that enables you to access SAP API Management using any
HTTP client. The API enables programmatic scripting to perform development tasks, such as deployment of API
proxies. The RESTful API also provides access to low-level capabilities that are not exposed by the management
UI for reasons of usability. The API is designed to be lightweight and to impose few restrictions on the client code
that consumes it.
As a RESTful API, the SAP API Management Platform follows a pattern in which capabilities are exposed as API
'resources'. API 'resource' is a term derived from the web application description language (WADL) specification.
According to the WADL specification, a RESTful application can be described as a set of resources.
Each resource, in turn, defines a set of methods that act on it. Some examples of the resources exposed by the
SAP API Management API are API proxies, API products, apps, and developers.
Following RESTful principles, you can call HTTP GET, POST, PUT, and DELETE methods on any of the API
resources.
o GET: Retrieves a list of resources, or the profile of a specific resource.
Your organization name is used in the base path for the requests to the SAP API Management Platform API. You
can locate your organization name under User Settings in the SAP API Management UI.
To retrieve a list of API proxies in your organization, you would call GET on:
http://<host:port>/v1/organizations/apibuilders/apis
Many resources are segregated according to environments. Two environments are provided by default: test and
prod. An example of a resource that is scoped by environment is Cache. A default Cache, called 'mycache' is set
up in every environment. You can list Caches by calling GET on the Cache resource as follows:
https://<host:port>/v1/organizations/apibuilders/environments/test/caches
http://<host:port>/v1/organizations/apibuilders/environments/prod
Passing Credentials
The API enforces HTTP Basic Authentication. You always need to pass in your username and password for your
account. These can be passed in as a Base64 encoded header, or as parameters (as demonstrated below) in an
HTTP client. The following is an example of an HTTP Basic Authentication header:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
To consume the SAP API Management API you require an HTTP client. Many examples in the documentation
provide sample API requests using cURL, a widely-used HTTP client. If you need to install cURL, you can download
it from http://curl.haxx.se.
If you cut and paste a cURL command from the doc to your terminal, you must replace the following variables in
the command with information for your SAP API Management account:
• email: The email for your account
• password: The password for your account in an account
• myorg: The name of your organization
• host:port : The address of the system where the SAP API Management API Platform is installed.
Example
$ curl -k http://<host:port>/v1/organizations/{org_name}/apis -u myname:mypass
If you are using the SAP API Management samples, set the values for your organization, username, and password
in the file /setup/setenv.sh. Once you have done so, you can run the simplified deploy and invoke scripts
provided for each sample API proxy.
Note
Calls to the management API support gzip compression on responses. If you set 'Accept-Encoding: gzip,
deflate' in your API calls, any response greater than 1024 bytes gets returned in gzip format.
Every organization using SAP API Management automatically has at least two environments they can use to
develop, test, and deploy APIs: 'test' and 'prod'. Use the test environment to develop and test your APIs before
making them publicly available. Only your internal developers can access APIs deployed to the test environment.
Deploy your APIs to the prod environment to make them publicly available to app developers.
2.4 Testing
SAP API Platform provides a trace tool that lets you debug end-to-end request and response flows. The trace
results display request and response headers and payloads, policy execution, variable values, and any errors that
may have occurred during the flow.
Key data points for use in troubleshooting:
• Timestamps: Use timestamps to see how long each step takes to execute. Comparing timestamps helps you
isolate the policies that are taking the longest to execute that are slowing down your API calls.
• Base path: By verifying the base path, you can ensure that a policy is routing the message to correct server.
• Results of policy execution: These results let you see if the message is being altered as expected, such as if
the message is being transformed from XML to JSON, or if the message is being cached.
Each Trace session is broken down into the following major steps:
• Original request received from client: Displays the verb and URI path of the request from the client app,
headers, body data, and query parameters.
• Request sent to your backend service: Displays the request message sent to the backend service by the API
proxy.
• Response returned by the backend service: Displays the response headers and payload returned by the
backend service.
• Final response sent to client: The response message returned to the requesting client app once the
response flow has executed.
You expose APIs on SAP API Management by implementing API proxies. An API proxy is a bundle of XML
configuration files and code (such as JavaScript) that implements the facade for your backend HTTP services. API
proxies decouple the developer-facing API from your backend services, shielding developers from code changes
and enabling you to innovate at the SAP API Management without impacting internal applications and
development teams. As development teams make backend changes, developers continue to call the same API
without any interruption.
API proxies manage request and response messages using a 'pipeline' processing model that defines 'Flows'. To
customize the behavior of your API, you attach Policies to request and response Flows.
In an API proxy configuration, there are two types of endpoints:
• ProxyEndpoint: This configuration manages interactions with apps that consume your API. You configure the
ProxyEndpoint to define the URL of your API. You usually attach Policies to the ProxyEndpoint to enforce
security, quota checks, and other types of access control and rate-limiting.
• TargetEndpoint: This configuration manages interactions with your backend services on behalf of consumer
apps. You configure the TargetEndpoint to forward request messages to the proper backend service. You
usually attach Policies to the TargetEndpoint to ensure that response messages are properly formatted for
the app that made the initial request.
You can visualize API proxies as shown by the graphic below. A basic request and response exchange between an
app (HTTP client) and a backend service is managed in an API proxy by a ProxyEndpoint and TargetEndpoint.
An API proxy consists of a bundle of XML configuration files and code (such as JavaScript and Java). SAP API
Management provides several ways for you to create API proxies, including:
• Using the SAP API Management UI to define an API proxy in a Graphical User Interface (GUI).
• Creating XML files, along with any other supporting files, that define your API proxy and then importing them
into SAP API Management.
• Using the SAP API Management's API to create your API proxies by making a series of REST requests to SAP
API Management.
SAP API Management enables you to control API behavior without writing any code by using policies. A policy is
like a module that implements a specific, limited management function as part of the proxy request/response
flow. Policies are designed to let you add common types of management capabilities to an API easily and reliably.
Policies provide features like security, rate-limiting, transformation, and mediation capabilities, saving you from
having to code and maintain this functionality on your own.
API proxies manage request and response messages using a pipeline processing mode, where the pipeline
consists of a sequence of flows. You attach SAP API Management policies to different flows in the pipeline,
depending on the type of policy and the action that you want to perform.
1. PreFlow
PreFlows always execute first, and the logic you attach in the PreFlow applies to all calls made to the API proxy.
They are useful when you need to make sure that a policy or code executes before anything else happens. For
example, you usually don't want an API proxy to waste any resources on an unauthenticated user. Also, you don't
want to service an app that has exceeded its quota. To support these requirements, you put security and quota
policies in the PreFlow segment. That way, you don't need to worry about a condition failing to evaluate. The
policies will always execute before any other processing takes place.
2. Conditional Flow
API proxy programming starts to get interesting when you implement 'branching' logic for an API. For example,
you might want to convert XML to JSON only when the requesting app is running on a mobile device; or create a
new HTTP response header when the /foo API resource is called; or you might want to return a targeted ad based
on the data in the user's request. You can do this by setting up conditional flows.
3. PostFlow
As with PreFlow, the logic you attach to the PostFlow applies to all calls made to the API proxy. PostFlow is useful
when you need to log some data, send a notification that something happened, transform the message format,
and so on.
A route determines the path of a request from the ProxyEndpoint to the TargetEndpoint. Included in the route is
the URL used to access the API ProxyEndpoint and the URL of the backend service defined by the TargetEndpoint.
After you create an API proxy on SAP API Management, the default URL that an app uses to access the proxy has
the form:
http://{org-name}-{env-name}.<host:port>/{base-path}/{resource-path}
https://{org-name}-{env-name}.<host:port>/{base-path}/{resource-path}
where:
{org-name} is your organization name. This name is created when you create an account on SAP API
Management.
{env-name} is the SAP API Management environment name. By default, all SAP API Management organizations
created in the cloud are provisioned with two environments: 'test' and 'prod'. When deploying an API proxy, you
can choose to deploy it to one or both environments.
{base-path} and {resource-path} are defined when you create the API proxy.
When a request comes in to SAP API Management, SAP API Management parses the URL to direct the request to
the correct ProxyEndpoint. For example, the following URL is used to access an API proxy on SAP API
Management:
http://myOrg-prod.<host:port>/v1/weather/forecastrss
A virtual host defines the domains and ports on which an API proxy is exposed. A virtual host also defines whether
the API proxy is accessed by using the HTTP protocol, or by the encrypted HTTPS protocol.
The second part of the URL, /v1/weather, is determined by the <BasePath> element in the ProxyEndpoint. The
base path must be unique to the API proxy for the environment so that two API proxies do not have the same base
path.
The third part of the URL, /forecastrss, is a resource defined by the API proxy with the corresponding Conditional
Flow defined by the <Flows>tag.
Direct URL
A ProxyEndpoint can directly invoke a backend service, bypassing any named TargetEndpoint configuration. For
example, the following<RouteRule> always makes an HTTP call to http://api.mycompany.com/myAPI:
<RouteRule name="default">
<URL>http://api.mycompany.com/myAPI</URL>
</RouteRule>
However, because there is no TargetEndpoint, you can only add policies to the flows defined by the
ProxyEndpoint.
Single target
In a single target definition, the ProxyEndpoint references a single TargetEndpoint definition by name, as shown in
the figure above:
<RouteRule name="default">
<TargetEndpoint>default</TargetEndpoint>
</RouteRule>
Conditional targets
The <RouteRule> tag lets you direct a request to a target based on a condition. You can use flow variables, query
parameters, HTTP headers, message content, or contextual information such time of day and locale to determine
the target endpoint. For example, you might include a geographical area, such as US and UK, in a request URL.
You can then route a request to a target endpoint based on the region.
The following route rule evaluates an HTTP header in a request. If the HTTP header routeTo has the
value TargetEndpoint1, then the request is forwarded to the TargetEndpoint named TargetEndpoint1. If not, then
the request is forwarded to TargetEndpoint2.
<RouteRule name="MyRoute">
<Condition>request.header.routeTo = "TargetEndpoint1"</Condition>
<TargetEndpoint>TargetEndpoint1</TargetEndpoint>
</RouteRule>
<RouteRule name="default">
<TargetEndpoint>TargetEndpoint2</TargetEndpoint>
</RouteRule>
If you have multiple route rules, create one as the 'default', that is, as a route rule with no condition. Ensure that
the default route rule is defined last in the list of conditional Routes because rules are evaluated top-down in the
ProxyEndpoint.
Null route
A null route supports scenarios in which the request message does not need to be forwarded to a TargetEndpoint.
This is useful when the ProxyEndpoint performs all of the necessary processing, for example by using JavaScript
to call an external service.
The following example defines a null route:
<RouteRule name="GoNowhere"/>
When you make a request to an API proxy, you can pass any or all of the following information, depending on the
way the API proxy is configured:
• Request headers
• Query params
• Form data
• XML or JSON payloads
• Resource URIs
The same is true for the response received by SAP API Management from the backend service. By default, all data
received in the response is passed unchanged to the app that originated the request.
A client app then makes a GET request to the API proxy by using the following cURL command:
curl -X GET http://myOrg-prod.<host:port>/v1/weather/forecastrss?w=12797282
Notice that this request contains the resource "forecastrss" and one query param, "w". SAP API Management
parses the request as shown below and assigns parts of the request to flow variables:
{request.verb} {proxy.basepath}/{proxy.pathsuffix}?{request.querystring}
Note
There are many different flow variables created during the processing of a request and response.
{request.verb} {target.basepath}/{proxy.pathsuffix}?{request.querystring}
Notice how the resource and query params specified in the request are automatically included in the request to
the backend server. From the definition of the TargetEndpoint, the request then has the form:
Like query params, any headers or form params that you include in the request to the API proxy are passed on to
the backend server. For example, you make the request below that includes a header:
In both examples, the headers and form data are passed unchanged to the backend service. The headers are
represented by flow variables such asrequest.headers.count and request.headers.names. The form data is
represented by flow variables such as request.formparam.countand request.formparam.names.
The same is true for data in the response. As part of processing the response, the API proxy might want to modify
the data before returning it to the requesting app.
SAP API Management defines several policies that you can use to process the request and response data. These
policies include:
• Assign Message policy: Creates or modifies HTTP request or response messages during an API proxy flow.
Also creates and populates new flow variables.
• Extract Variables policy: Extract content from messages, including headers, URI paths, payloads, and query
parameters, for use in a condition statement. The policy then applies a text pattern to message content and
upon finding a match sets a designated variable.
• JSON to XML policy and XML to JSON policy: Converts messages from JavaScript Object Notation (JSON) to
the extensible markup language (XML) format, or vice versa.
• Java Callout policy, JavaScript policy, Python Script policy, Regular Expression Protection policy: These
policies let you write a script to access flow variables containing request and response data.
Every organization has a unique software development lifecycle (SDLC). It is often necessary to synchronize and
align API proxy deployment with the same processes that you use today for developing, testing, and deploying
other applications.
API Services provides tools and RESTful APIs that enable you to integrate API proxy deployment and
management into your organization's SDLC. A common usage of the RESTful API is to write scripts or code that
programmatically deploy API proxies, or that migrate API proxies from one environment to another, as part of a
larger automated process that also deploys or migrates other applications. API Services makes no assumptions
about your SDLC (or anyone else's, for that matter). Rather, it exposes atomic functions that can be coordinated
by your development team to automate and optimize your API development lifecycle.
API Services APIs are documented in the API Reference.
Environments
Every organization on SAP API Management has at least two deployment environments that are available for API
proxies: 'test' and 'prod'. The distinction between the two environments is arbitrary — each environment is simply
identified by a different set of network addresses (URLs). The goal is to provide you with a domain in which you
can build and verify API proxies before the API is exposed to external developers.
You can leverage these environments to synchronize API proxy development processed with your SDLC. Each
environment is defined by a network address, enabling you to segregate traffic between the API proxies that you
are working on, and those that are being accessed by apps at runtime. The network addresses available for each
environment is defined in the set of VirtualHosts available in that environment.
<HTTPProxyConnection>
<BasePath>/v0/weather</BasePath>
<Properties/>
<VirtualHost>default</VirtualHost>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>
By deleting the default VirtualHost from the ProxyEndpoint configuration, you create an API proxy that listens
only on HTTPS and not on HTTP.
<HTTPProxyConnection>
<BasePath>/v0/weather</BasePath>
<Properties/>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>
You can see which VirtualHosts are available in an environment by selecting Environments in the management UI
main menu.
Environments also provide segregation of data and resources. You can, for example, set up different caches in
test and prod, which can be accessed only by API proxies executing in that environment. Additionally, API keys
that are issued in the test environment are not valid in the prod environment, and vice-versa.
When you create an API proxy you'll need to decide which environment you'll be working in. You can choose to
create a new API proxy on production, but that is not recommended as you may expose an API to developers
before it's ready. In general you want to start by creating an API proxy in testwhich, after testing, you then
'promote' to prod.
Note
Depending on your role, you may not be able to deploy to all environments. For example, the 'user' role
can only deploy to the testenvironment. If you're an administrator you can deploy to any environment.
As you work on an API proxy, API Services saves iterations of your configuration as revisions. When you deploy an
API proxy, you choose a specific revision to deploy. Typically, you deploy the most recent revision, and, if
necessary, revert to the previous revision number. You can choose where to deploy those revisions. For instance,
you can promote a revision to prod to allow developers to start working with your API. At the same time, you may
be iterating multiple revisions on test, where you're adding features or fine-tuning policies. Then, when you're
ready, you can deploy the new revision to prod, overwriting the existing revision on that environment. Using this
method, you can always have a live revision of your API available to developers while you're developing.
Promotion to prod
When an API proxy has been fully implemented and tested, it is ready to be promoted to 'prod'. The revision of the
API proxy in test will be used to overwrite the revision of the API proxy deployed on prod.
API Services provides capabilities to ensure seamless deployment of API proxies, minimizing the impact on apps
and end users during the deployment procedure.
Scripting deployment
The SAP API Management UI enables you to deploy API proxies to prod directly from the API proxy builder.
However, in many situations the requirements for security, reliability, and consistency will mandate that
development teams script deployment procedures. To do so, you can write code and scripts that invoke the
RESTful API exposed by API Services.
Environment resources
For additional control during promotion, it is recommended that you only iterate on API proxies in test, and make
as few changes as necessary to API proxies deployed in prod.
To do so, you need to ensure that certain resources associated with each environment are configured in such a
way that they can remain static in an API proxy configuration.
• Target URLs: It is common for API proxies to call different backend URLs during testing and production. You
can use TargetServer configurations to create environment-independent TargetEndpoint configurations.
• Caches and Key/value maps: Both persistence resources are scoped by environment. You should ensure that
naming conventions are used to enable API proxies to store data without requiring configuration changes
during promotion.
• ServiceCallout targets: Service callouts may use different targets depending on the environment, if, for
example, a ServiceCallout in the test environment consumes a demo service.
To make API proxy configurations environment-independent, you can also use conditional statements.
Conditional statement built with theenvironment.name variable can be used to evaluate the current environment
before enforcing a policy or before routing to a URL on the backend.
There are several concepts that are common ideas with a unique meaning in SAP API Management.
Term Definition
API An 'application programming interface' is an architecture that makes it easy for one
application to 'consume' capabilities or data from another application.
By defining stable, simplified entry points to application logic and data, APIs enable developers
to easily access and reuse application logic built by other developers. In the case of 'Web APIs',
that logic and data is exposed over the network. Since applications that consume APIs are
sensitive to changes, APIs also imply a 'contract'. The contract provides some level of
assurance that, over time, the API will change in a predictable manner.
API proxy A facade on SAP API Management for one or more APIs, generic HTTP services, or
applications (such as Node.js).
An API proxy is implemented as a set of configuration files, policies, and code that rely on a set
of resources provided by SAP API Management. API proxies can be generated and configured
using the SAP API Management UI, or they can be implemented locally in a text editor or IDE.
The facade provided by an API proxy decouples the developer-facing API from 'backend'
services, shielding developers from code changes and enabling innovation at the SAP API
Management without impacting your internal development teams. As development teams
make backend changes, developers continue to call the same interface uninterrupted. SAP API
Management enables you to expose multiple interfaces to the same API, freeing you to
customize the signature of an API to meet the needs of various developer niches
simultaneously.
API base path APIs defined by network addresses and URIs. An API is made up of a 'base path' and a set of
and resources 'API resources'. Every API proxy defines a base path and, optionally, multiple API resource
paths. You can think of an API simply as a set of URIs, all of which share a common base path.
To make it easier to manage your APIs, SAP API Management augments these raw URIs with
display names and descriptions. SAP API Management enables you to attach policies and code
to URIs, enabling fine-grained control and management of the behavior of your APIs.
API product A collection of API resources (URIs) combined with a quota, or 'service plan', which is
published to app developers at design time. API products can in turn be bundled into API
packages for monetization.
An API key is bound to one or more API products, enforcing a binding between an app and the
bundle of URIs that the app is permitted to consume.
API package A collection of API products that are presented to developers as a bundle, and typically
associated with a rate plan defined in monetization.
app An abbreviation of 'application'. The term 'app' has come to refer to mobile applications that
consume APIs. Developers implement apps in a variety of programming languages, and using
various technologies and platforms. Developers who want to consume APIs register apps in an
API provider's organization on SAP API Management.
When the app is registered, SAP API Management generates an API key and secret that
identify the app. The developer embeds the API key in the app, which presents the key when
environment A runtime execution context for API proxies. An API proxy must be deployed to an
environment before the API it exposes is accessible over the network. By default,
organizations are provisioned with two environments: 'test' and 'prod'.
The 'test' environment is typically used for deploying API proxies during development.
The 'prod' environment is typically used for promoting API proxies from the test environment
after they have been fully developed and tested.
organization A container for all the objects in an SAP API Management account, including API proxies, API
products, API packages, apps, and developers.
A user account is required for each organization for which you are a member. (Most users will
have an account in only one organization.) You need to supply your credentials (username and
password) and the name of your organization with each API request you submit.
policy A processing step that executes as an atomic, reusable unit of logic within an API proxy
processing flow.
Typical policy-based functionality includes transforming message formats, enforcing access
control, calling remote services for additional information, masking sensitive data from
external users, examining message content for potential threats, caching common responses
to improve performance, and so on.
Policies may be conditionally executed based on the content or context of a request or
response message. For example, a transformation policy may be executed to customize a
response format if the request message was sent from a smartphone.
API resource A RESTful concept, a resource path is a uniform resource identifier (URI) that identifies the
path network path to a given resource.
revision A numbered, version-controlled package of configuration and policies bundled into an API
Proxy. This term is distinguished from 'version', which is the developer-facing API interface.
See version above.
The purpose of this document is to provide a set of standards and best practices for developing with SAP API
Management. The topics that are covered here include design, coding, policy use, monitoring, and debugging. The
information has been gathered by the experience of developers working with SAP API Management to implement
successful API programs. This is a living document and will be updated from time to time.
Framework-style coding
Framework-style coding involves storing API proxy resources in your own version control system for reuse across
local development environments. For example, to reuse a policy, story it in source control so that developers can
sync to it and use it in their own proxy development environments.
• To enable DRY ("don't repeat yourself"), where possible, policy configurations and scripts should implement
specialized, reusable functions. For example, a dedicated policy to extract query parameters from request
messages could be called ExtractVariables.ExtractRequestParameters. A dedicated policy to inject
CORS headers could be called AssignMessage.SetCORSHeaders. Those policies could then be stored in
your source control system and added to each API proxy that needs to extract parameters or set CORS
headers, without requiring you to create redundant (and hence less manageable) configurations.
• Clean up unused policies and resources (JavaScript, Java, XSLT, etc.) from API proxies, especially large
resources that have the potential to slow down import and deploy procedures.
Naming Conventions
• The Policy name attribute and the XML policy file name must be identical.
• The Script and ServiceCallout policy name attribute and the name of the resource file should be identical.
• DisplayName should accurately describe the policy’s function to someone who has never worked with that
API proxy before..
• Name policies according to their function, for
example AssignTargetAuthHeader or AssignMessage.TargetAuthHeader,RaiseFault.InvalidUser.
• Use proper extensions for resource files, .js for JavaScript, .py for python, and .jar for Java JAR files.
• Variable names should be consistent. If you choose a style, such as camelCase or under_score, use it
throughout the API proxy.
• Use variable prefixes, where possible, to organize variables based on their purpose, for
example, Consumer.username and Consumer.password.
Construct Flows in an organized manner. Multiple Flows, each with a single condition, are preferable to multiple
conditional attachments to the same PreFlow and Postflow.
As a 'failsafe', create a default API proxy with a ProxyEndpoint BasePath of /. This can be used to redirect base
API requests to a developer site, to return a custom response, or perform another action more useful than
returning the default CLASSIFICATION_ERROR.
Use TargetServer resources to decouple TargetEndpoint configurations from concrete URLs, supporting
promotion across environments.
If you have multiple RouteRules, create one as the 'default', that is, as a RouteRule with no condition. Ensure that
the default RouteRule is defined last in the list of conditional Routes. RouteRules are evaluated top-down in
ProxyEndpoint.
To prevent memory issues in SAP API Management, message payload size is restricted to 3MB.
Exceeding those sizes results in a protocol.http.TooBigBody error.
Following are the recommended strategies for handling large message sizes in SAP API Management:
• Stream requests and responses. Note that when you stream, policies no longer have access to the message
content.
• In SAP API Mangement deployments, edit the message processor http.properties file to increase the limit
in the HTTPResponse.body.buffer.limit parameter. Be sure to test before deploying the change to
production.
Fault Handling
• Leverage FaultRules to handle all fault handling. (RaiseFault policies are used to stop message Flow and send
processing to the FaultRules Flow.)
• Within the FaultRules Flow, use AssignMessage policies to build the fault response, not RaiseFault policies.
Conditionally execute AssignMessage policies based on the fault type that occurs.
• Always includes a default 'catch-all' fault handler so that system-generated faults can be mapped to
customer-defined fault response formats.
• If possible, always make fault responses match any standard formats available in your company or project.
• Use meaningful, human-readable error messages that suggest a solution to the error condition.
Key/Value Maps
• Use key/value maps only for limited data sets. They are not designed to be a long-term data store.
• Consider performance when using key/value maps as this information is stored in the Cassandra database.
Response Caching
• Do not populate the response cache if the response is not successful or if the request is not a GET. Creates,
updates, and deletes should not be cached. <SkipCachePopulation>response.status.code != 200 or
request.verb != “GET”</SkipCachePopulation>
• Populate cache with a single consistent content type (for example, XML or JSON). After retrieving a
responseCache entry, then convert to the needed content type with JSONtoXML or XMLToJSON. This will
prevent storing double, triple, or more data.
• Ensure that the cache key is sufficient to the caching requirement. In many cases, the request.querystring can
be used as the unique identifier.
• Do not include the API key (client_id) in the cache key, unless explicitly required. Most often, APIs secured
only by a key will return the same data to all clients for a given request. It is inefficient to store the same value
for a number of entries based on the API key.
• Set appropriate cache expiration intervals to avoid dirty reads.
• Ideally, the response cache policy should be attached to the ProxyEndpoint response PostFlow, before any
format translations (XMLToJSON, JSONToXML)
• The response cache policy to lookup the cache entry should occur in the ProxyEndpoint request PreFlow.
Avoid implementing too much logic, other than cache key generation, before returning a cache entry.
Otherwise, the benefits of caching are minimized.
• In general, you should always keep the response cache lookup as close to the client request as possible.
Conversely, you should keep the response cache population as close to the client response as possible.
JavaScript
• Use JavaScript if it’s more intuitive than SAP API Management policies (for example, when
setting target.url for many different URI combinations).
• Complex payload parsing such as iterating through a JSON object and Base64 encoding/decoding.
• JavaScript policy has a time limit, so infinite loops are blocked.
Java
• Use Java if performance is the highest priority, or if the logic cannot be implemented in JavaScript.
• Include Java source files in source code tracking.
Python
• Do not use Python unless absolutely required. Python scripts can introduce performance bottlenecks for
simple executions, as it is interpreted at runtime.
JavaScript
• JavaScript on the API Platform supports XML via E4X.
Java
• When accessing message payloads, try to
use context.getMessage() vs. context.getResponseMessage or context.getRequestMessage. This ensures
that the code can retrieve the payload, in both request and response flows.
• Import libraries to the SAP API Management organization or environment and do not include these in the JAR
file. This reduces the bundle size and will let other JAR files access the same library repository.
• Import JAR files using the SAP API Management resources API rather than including them inside the API
proxy resources folder. This will reduce deployment times and allow the same JAR files to be referenced by
multiple API proxies. Another benefit is class loader isolation.
• Do not use Java for resource handling (for example, creating and managing thread pools).
• Use @IOIntensive annotation for all Java classes. This will cause the class to run in a separate thread pool.
Otherwise it runs in an I/O thread, which is in the core thread pool and has the potential to block the CPU.
Python
• Throw meaningful exceptions and catch these properly for use in SAP API Management fault responses
AccessEntity Policy
For better performance, look up apps by uuid instead of app name.
Logging
Use a common syslog policy across bundles and within the same bundle. This will keep a consistent logging
format.
Monitoring
Cloud customers are not required to check individual components of SAP API Management (Routers, Message
Processors, etc.). SAP API Management’s Global Operations team is thoroughly monitoring all of the
components, along with API health checks, given health check requests by the customer.
Trace
The trace tool in the SAP API Management UI is useful for debugging runtime API issues, during development or
production operation of an API.
Security
• Use IP address restriction policies to limit access to your test environment. Whitelist the IP addresses of you
development machines or environments.
• Always apply content protection policies (JSON and or XML) to API proxies that are deployed to production.
ServiceCallouts
• Don't make ServiceCallouts to other API proxies in the same organization, including recursive callouts back
into the same API proxy.
• Build a ServiceCallout request message using the AssignMessage policy, and populate the request object in a
message variable. (This includes setting the request payload, path, and method.)
• The URL that is configured within the policy requires the protocol specification, meaning the protocol portion
of the URL, https:// for example, cannot be specified by a variable. Also, you must use separate variables for
the domain portion of the URL and for the rest of the URL. For example: https://{domain}/{path}
• Store the response object for a ServiceCallout in a separate message variable. You can then parse the
message variable and keeps the original message payload intact for use by other policies.
SAP API Management enables you to quickly expose backend services as APIs. You do this by creating an API
proxy that provides a facade for the backend service that you want to expose. You only need to provide the
network address for the backend service, along with some information that API Platform uses to model the API
that will be exposed to developers.
The API proxy that you create on SAP API Platform decouples your backend service implementation from the API
that developers consume. This shields developers from future changes to your backend services. As you update
backend services, developers, insulated from those changes, can continue to call the API uninterrupted.
This topic shows you how to create a simple API proxy that runs on SAP API Management.
The easiest way to create an API proxy is using the API proxy builder tool, which is available in the SAP API
Management UI.
1. Log in into the SAP API Management UI.
2. From the main menu, select APIs > API Proxies.
A list of all API proxies in your organization displays.
3. To create a new API proxy, select add (+) API Proxy button.
The New API Proxy form is displayed.
Use this form to provide API Platform with the information it needs to generate an API proxy and, optionally,
to add some minimal features to the API that is exposed.
This form enables you to create an API proxy from the following sources:
o An existing HTTP service (this could be a JSON or XML API)
o An existing API proxy bundle
o A WSDL file
o An API proxy with no API backend ("No target")
o A Node.js application
The following sections describe how to create an API proxy using each source.
You can use this capability to import any API proxies that you or other developers have configured.
1. In the New API Proxy dialog box, under Choose Your Starting Point section:
1. Select the API Bundle.
2. Select Choose File.
3. Navigate to the ZIP file containing the API proxy configuration
2. Under Identify Your API Proxy, enter a descriptive name for your API.
3. Select Build
In response, you should see an acknowledgment that your new API proxy was successfully imported. API
Platform automatically deploys the imported API proxy to the 'test' environment in your organization. The API
exposed by the API proxy is available to be invoked.
You can copy an existing API proxy to a new API proxy, or backup and existing API proxy to a set of XML files as an
API proxy bundle. Once exported to a bundle, you can import the API proxy to a new proxy, as described above.
You can specify that one proxy is the target endpoint of another, effectively connecting the two proxies in a proxy
chain.
You might find this useful when you have a proxy that offers some discrete low-level functionality that one or more
other proxies will consume. For example, a proxy that exposes create/read/update/delete operations with a
backend data store could be the target proxy for multiple other proxies that expose the data to clients.
To minimize network overhead when calling one proxy from another, you can specify that one proxy is the local
target endpoint of the other. This kind of connection, called proxy chaining, gives you a local connection between
two proxies. This local connection is more efficient because it bypasses network features such as load balancers,
routers, and message processors. When you specify a proxy as a local target endpoint, processing flows to that
proxy as it would to another kind of target.
Note:
Proxies you want to connect in this way must be in the same organization and environment. When the proxy
you're connecting with is outside this scope, consider connecting to it as an external resource using
the HTTPTargetConnection element.
You connect proxies by specifying that one is a local target endpoint of the other. You can create a local
connection between proxies in two ways:
• By specifying the name of the target proxy and a ProxyEndpoint name
• By specifying a path to the target proxy endpoint
You can specify the target proxy by name. You might find that this is most useful when you're creating the
connection from the start and developing the proxies together. If you don't know the name (or the name might
change), consider connecting with the target proxy's endpoint path, as described below.
When you connect to a target proxy by name, you specify the proxy's name and the name of its ProxyEndpoint.
The following example specifies a target proxy called data-manager, along with the ProxyEndpoint name
exposed by data-manager.
<TargetEndpoint name="datamanager">
<PreFlow name="PreFlow">
<!-- PreFlow policies -->
</PreFlow>
<PostFlow name="PostFlow">
<!-- PostFlow policies -->
</PostFlow>
<LocalTargetConnection>
<APIProxy>data-manager</APIProxy>
<ProxyEndpoint>default</ProxyEndpoint>
</LocalTargetConnection>
</TargetEndpoint>
You can specify the target proxy by its endpoint path. You might want to do it this way when you don't know the
proxy name, or when the name might change.
If your proxy is simply the consumer of the target proxy -- such as when you're not developing both -- the path
might be the most reliable way to connect. For example, if the proxy you're connecting to is developed and
maintained by another team, you might want to connect using a reliable endpoint path.
The following example specifies a target proxy at /v1/streetcarts/foodcarts/data-manager, where the
host is assumed to be the same as the current proxy
<TargetEndpoint name="datamanager">
<PreFlow name="PreFlow">
<!-- PreFlow policies -->
You can create proxy chaining connections using the SAP API Management Edge console.
1. Open the proxy that will be consuming the target proxy.
2. In the Navigator, click the plus sign next to Target Endpoints.
3. In the New Target Endpoint dialog, enter the name of the target endpoint.
4. Beneath the Target Endpoint Name box, select one of the following:
• Proxy Chaining to select from a list of proxies already in the organization and environment.
1. In the Proxy Name dropdown, select the target proxy.
2. In the Proxy Endpoint box, enter the target proxy endpoint path you want to connect to.
• Path Chaining to enter the target proxy base path, such a /mypath/myproxy/myendpoint.
5. Click Add.
You can create two kinds of SOAP proxies in SAP API Management. One generates a RESTful interface to the
backend SOAP service and the other performs a "pass through" of the SOAP message to the backend. For details,
see Exposing a SOAP service as an API proxy.
When you add an API proxy for an existing backend service or import an existing API bundle, the New API
Proxy page displays an Add Features section in which you can add features to your API such as security and
support for CORS.
Note
If you import an API bundle, then you are responsible for configuring security in the bundle. The UI does
not prompt you to add security when importing the bundle.
Check Security with API Keys to add simple API key verification to the API proxy that you are defining. In
response, the SAP API Management adds a VerifyAPIKey policy and an AssignMessage policy to your API proxy.
The VerifyAPIKey policy validates API keys presented by requesting apps. The AssignMessage policy strips the
API key, supplied in the API call as a query parameter, from the request forwarded to the backend server.
If you select Secure with OAuth v2.0 Access Tokens, SAP API Management will automatically add two policies to
your API proxy: one policy to verify an access token and another policy to strip the access token from the
message before forwarding it to your backend service. To learn how to obtain an access token, see OAuth.
When you check Secure with API Keys, the New API Proxy page displays an additional checkbox:
Impose Quota per Developer. Check this to add a Quota policy to your API proxy that enforces a limit on the traffic
to your API from individual apps.
CORS (Cross-origin resource sharing) is a standard mechanism that allows a Web browser to make direct
requests to another domain. The CORS standard defines a set of HTTP headers that Web browsers and servers
use to implement cross-domain communication.
You can add support for CORS to your API by selecting the Enable Direct Browser Access for your API checkbox
under Add Features. For more detailed information about CORS support, including adding CORS preflight support
to a proxy, see Adding CORS Support to an API proxy.
Flows are the basic building blocks of API proxies. Flows enable you to program the behavior of an API by letting
you configure the sequence in which policies and code are executed by an API proxy.
For a conceptual overview of flows, see Understanding flows.
SAP API Management comes with many different types of predefined policies to implement security, manage
traffic, and manipulate messages. In addition, policies let you add your own custom code to completely customize
message processing.
For example:
• Attach an OAuth security policy to the request PreFlow of the ProxyEndpoint. Because the ProxyEndpoint's
request PreFlow is the first flow in the pipeline, you can immediately reject a request if it violates your security
policies.
• Attach a JSON to XML conversion policy to the response PostFlow of the TargetEndpoint to convert a
response from JSON to XML.
• Attach a JavaScript policy to a Conditional Flow of the ProxyEndpoint to execute JavaScript code to process
the request
Once you have created a conditional flow, it is available for Policy attachment. When you select New > Policy after
you create the flow, you will see an additional option in the list of flows. As shown below, when adding a Quota
policy, you now have the option to attach the Policy to the flow called Flow-1, which you just created.
By attaching the Policy to Flow-1, you are configuring the API proxy to enforce the Quota Policy only for requests
submitted using the GET verb. The Quota will not be enforced for POSTs, PUTs, etc.
The following ProxyEndpoint definition shows the underlying source XML with a policy named quota-2 on
the request PreFlow of the ProxyEndpoint:
<ProxyEndpoint name="default">
<PreFlow name="PreFlow">
<Request>
<Step>
<Name>quota-2</Name>
</Step>
Any policies attached to the PreFlow or PostFlow are always executed. However, the policies in a conditional flow
are executed only if the flow's condition evaluates to true.
During the processing of a request and response, only one conditional flow is executed per segment--the first flow
whose condition evaluates to true. That means you can have one conditional flow executed as part of each of the:
For example, the following ProxyEndpoint definition shows a conditional flow that is executed by the
ProxyEndpoint on any HTTP GET request to the API proxy:
<ProxyEndpoint name="default">
<PreFlow>
<Request/>
<Response/>
</PreFlow>
<Flows>
<Flow name="Flow-1">
<Condition>request.verb="GET"</Condition>
<Request/>
<Response/>
</Flow>
</Flows>
<PostFlow>
In an API proxy, you can define a conditional flow that corresponds to a specific resource:
<ProxyEndpoint name="default">
<PreFlow>
<Request/>
<Response/>
</PreFlow>
<Flows>
<Flow name="Flow-1">
<Condition>(proxy.pathsuffix MatchesPath "/reports")</Condition>
<Request/>
<Response/>
</Flow>
<Flow name="Flow-2">
<Condition>(proxy.pathsuffix MatchesPath "/forecasts")</Condition>
<Request/>
<Response/>
</Flow>
</Flows>
<PostFlow>
<Request/>
<Response/>
</PostFlow>
...
</ProxyEndpoint>
In this brief example, you set up a flow that executes only when the request message is an HTTP GET.
To add a conditional flow, select the Develop view in the API proxy builder. Select New > Conditional Flow.
The New Conditional Flow form enables you name the flow and to add a condition. In this example, you add a
condition that evaluates the HTTP of the request message. You add a condition that will evaluate to true if the
HTTP verb is GET (as opposed to PUT, POST, etc.)
The form also enables you to add the flow to the ProxyEndpoint named default or the TargetEndpoint
named default.
Select the Proxy endpoint default option.
The new flow, called Flow-1, now appears in the Navigator menu.
Now observe the XML configuration for the ProxyEndpoint. Select Flow-1 in the Navigator menu.
You will see the following configuration.
<PreFlow name="PreFlow">
<Request/>
<Response/>
</PreFlow>
<Flows>
<Flow name="Flow-1">
<Request/>
<Response/>
<Condition>request.verb="GET"</Condition>
</Flow>
Conditional statements are a common control structure in all programming languages. Like a programming
language, API proxy configuration supports conditional statements for Flows, Policies, and RouteRules. By
defining conditional statements, you define dynamic behavior for your API. This dynamic behavior lets you do
things like converting XML into JSON only for mobile devices, or routing to a backend URL based on the
content type or HTTP verb of the request message.
This topic shows you how to use conditions to dynamically apply API management features at runtime,
without writing any code.
Conditional behavior is implemented in API proxies by using a combination of conditions and variables. A
conditional statement is created using a Condition element. The following is an empty condition:
<Condition></Condition>
To create a conditional statement, you add a conditional operator and a variable to create the following structure:
<Condition>{variable.name}{operator}{"value"}</Condition>
Supported conditional operators include = (equals), != (not equal), and > (greater than). For readability, you can
also write the conditionals as text: equals, notequals, greaterthan.
When working with URI paths you can use ~/ or MatchesPath. You can also use conditions to evaluate regular
expressions.
Variables
Conditions do their work by evaluating the values of variables. A variable is a property of an HTTP transaction
executed by an API proxy, or a property of an API proxy configuration itself. Whenever an API proxy gets a
request from an app, API Platform populates a long list of variables that are associated with things like system
time, the app's network information, HTTP headers on messages, the API proxy configuration, policy
executions and so on. This creates a rich context that you can use to setup conditional statements.
Variables always use a dotted notation. For example, HTTP headers on the request message are available as
variables called request.header.{header_name}. So to evaluate the Content-type header, you could use the
variablerequest.header.Content-type. For example request.header.Content-
type ="application/json" indicates that the variable value should be JSON.
Recommendation
API Platform automatically stores all HTTP headers and query parameters as variables that can be
accessed using request.header and request.queryparam variable prefixes.
To enable dynamic behavior, you can attach Conditions to Flows, Steps, and RouteRules.
When you attach a condition to a Flow, you create a 'conditional Flow'. Conditional Flows execute only when
the condition evaluates to true. You can attach as many Policies as you want to a conditional Flow. A
conditional Flow enables you to craft highly specialized processing rules for request or response messages
that meet certain criteria.
For example, to create a Flow that executes only when the request verb is a GET:
<Flows>
<Flow name="ExecuteForGETs">
<Condition>request.verb="GET"</Condition>
</Flow>
</Flows>
As shown in the example below, you can apply the condition to the Policy Step itself. The following Condition
causes the VerifyApiKey Policy to be enforced only if a request message is a POST.
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>request.verb equals "POST"</Condition>
<Name>VerifyApiKey</Name>
Once you have defined such conditional Flows, you can attach Policies to them, enabling an API proxy to
enforce one set of policies for GET requests, and another set of policies for POST requests.
Recommendation
The XML To JSON policy type defines a set of reasonable defaults, which means that you only need to add
configuration elements to craft XML into specific JSON structures.
Since you want to convert responses from XML to JSON, you need to configure a conditional response Flow to
perform the conversion. For example, to convert all responses from XML to JSON before they are returned to
the client app, configure the following ProxyEndpoint response Flow.
<Flows>
<Flow name="Convert-for-devices">
<Response>
<Step><Name>ConvertToJSON</Name></Step>
</Response>
</Flow>
</Flows>
When you invoke the API using the standard request, the response is formatted in JSON.
However, your goal is to only convert Weather reports into JSON when the requesting client is a mobile device. To
enable such dynamic behavior, you must add a conditional statement to the Flow.
The following example shows a single conditional flow named Convert-for-devices, configured in the
ProxyEndpoint response Flow. Add the Condition as an element to the entity to which the condition applies. In this
example, the condition is a component of the Flow. Therefore, the Flow will execute whenever the statement
evaluates to true.
<Flows>
<Flow name="Convert-for-devices">
<Condition>(request.header.User-Agent = "Mozilla")</Condition>
<Response>
<Step><Name>ConvertToJSON</Name></Step>
</Response>
</Flow>
</Flows>
For each request received from an app, API Platform stores the values of all HTTP headers present as variables. If
the request contains an HTTP header called User-Agent, that header and its value are stored as a variable called
request.header.User-Agent.
Given the ProxyEndpoint configuration above, API Platform checks the value of the request.header.User-
Agent variable to see whether the condition evaluates to true.
If the condition does evaluate to true, that is, the value of the variable request.header.User-
Agent equalsMozilla, then the conditional Flow executes and the XMLtoJSON policy called ConvertToJSON is
enforced. If not, the Flow is not executed, and the XML response is returned unmodified (in XML format) to
the requesting app.
Sample Conditions
Conditional Flow
<!-- this entire flow is executed only if the response verb is a GET-->
<Flow name="GetRequests">
<Condition>response.verb="GET"</Condition>
RESTful services are collections of API resources. An API resource is a URI path fragment that identifies some
entity that developers can access by calling your API. For example, if your service backend provides weather
reports and weather forecasts, your API might define two API resources: /reports and /forecasts.
Recommendation
The term resource is used in the Web Application Description Language (WADL) specification. This is just
for convenience. It doesn't necessarily imply any endorsement of WADL. According to WADL, a RESTful
API consists of a base path and any number of resource paths. Resources are sometimes called API
With an API proxy URL mapped to the base URL of the backend service (when you create the proxy), you can add
conditional flows to specific resources, such as the /reports and /forecasts resources mentioned earlier.
Let's say you wanted to have SAP API Management "do something" when calls come in to
the /reports or /forecasts resources. At this point you're not telling SAP API Management what to do, just that it
should be listening for calls to those resources. You do this with conditions. In your SAP API Management API
proxy, you can create conditional flows for /reports and /forecasts. For conceptual purposes, the following API
proxy XML shows what those conditions might look like.
<Flows>
<Flow name="reports">
<Description/>
<Request/>
<Response/>
<Condition>(proxy.pathsuffix MatchesPath "/reports") and
(request.verb = "GET")</Condition>
</Flow>
<Flow name="forecasts">
<Description/>
<Request/>
<Response/>
Those conditions say, "When a GET request comes in with /reports and /forecasts in the URL, SAP API
Management will do whatever you (the API developer) tell it to, through the policies you attach to those flows.
Now here's an example of telling SAP API Management what to do when a condition is met. In the following API
proxy XML, when a GET request is sent to https://<host>:<port>/mygreatweatherforecast/reports, SAP API
Management executes the "XML-to-JSON-1" policy in the response.
<Flows>
<Flow name="reports">
<Description/>
<Request/>
<Response>
<Step>
<Name>XML-to-JSON-1</Name>
</Step>
</Response>
<Condition>(proxy.pathsuffix MatchesPath "/reports") and
(request.verb = "GET")</Condition>
</Flow>
In additional to those optional conditional flows, each API proxy also comes with two default flows:
a <PreFlow> executed before your conditional flows, and a <PostFlow> executed after your conditional flows.
Those are useful for executing policies when any call is made to an API proxy. For example, if you want to verify an
app's API key with every call, regardless of the backend resource being accessed, you could put a Verify API Key
policy on the <PreFlow>.
Defining conditional flows to backend resources in an API proxy is completely optional. However, those
conditional flows give you the ability to apply fine-grained management and monitoring.
You will be able to:
For example, imagine that you need to apply different types of management to /developers than to /apps.
To do so, you add two API resources: /developers and /apps.
In the Develop view of the API proxy builder, select New > Resource.
In the Navigator menu, you can see that two flows have been created: Apps and Developers.
http://{org-name}-{env}.<host:port>/{proxy_path}/apps
will cause the condition to evaluate to true, and this flow, along with any associated policies, will execute.
You can further refine resource definitions by specifying the HTTP verb associated with a call:
For example you may need to treat the "create app" method differently than "list apps". To do so, specify the
HTTP verb associated with the API resource. In this example, you need to manage the Create App method, so
select the POST method.
Select Add.
Adding this API resource results in a new flow. The new flow is added to the ProxyEndpoint for the API proxy that
you are building. If you look at the ProxyEndpoint configuration, you will see that the following flow configuration
has been added:
<Flow name="CreateApp">
<Description>Creates an app</Description>
<Request/>
<Response/>
<Condition>(proxy.pathsuffix MatchesPath "/apps") and (request.verb =
"POST")</Condition>
</Flow>
For example, the following condition uses a Java regular expression to recognize calls made to the /apps resource
with or without a trailing forward slash (/apps or /apps/**):
<Condition>(proxy.pathsuffix JavaRegex "/apps(/?)") and (request.verb =
"POST")</Condition>
In some cases, you will have hierarchical API resources. For example, the Developer Services API provides a
method for listing all apps that belong to a developer. The URI path is:
/developers/{developer_email}/apps
You may have resources where a unique ID is generated for each entity in a collection, which is sometimes
annotated as follows:
/genus/:id/species
This path applies equally to the following two URIs:
/genus/18904/species
/genus/17908/species
To represent this structure in an API resource, you can use wildcards. For example:
/developers/*/apps
And
/genus/*/species
will resolve these hierarchical URIs as API resources appropriately.
In some cases, especially for deeply hierarchical APIs, you may simply want to resolve everything below a certain
URI fragment. To do so, use a double asterisk wildcard in your resource definition. For example, if you define the
following API resource:
/developers/**
That API resource will resolve the following URI paths:
/developers/{developer_email}/apps
/developers/{developer_email}/keys
/developers/{developer_email}/apps/{app_id}/keys
The benefit of defining API resources is that you gain the ability to apply policies to requests that invoke those
specific URIs, providing granular control over the data and services that your API proxy exposes. Additionally, SAP
API Management collects operation metrics specific to the API resources you define. By defining specific API
resources, you gain the visibility required to identify performance bottlenecks or error conditions as they affect
specific calls against your API.
Resources can be used to control access to specific assets or objects in your API. If you disable an API resource,
or if you add a security policy to it, you are effectively blocking all the apps that call that resource.
Flow variables are named references that hold state associated with an API transaction processed by SAP API
Management. They exist within the context of an API proxy flow, and they track state in an API transaction the way
named variables track state in a software program. Flow variables store information such as:
• The IP address, headers, URL path, and payload sent from the requesting app
• System information such as the date and time when SAP API Management receives a request
• Data derived when a policy executes. For example after a policy executes that validates an OAuth token, SAP
API Management creates flow variables that hold information like the name of the requesting application.
• Information about the response from the target system
Some variables are "built-in" to SAP API Management and are automatically populated whenever an API request
is received. They are available throughout an API transaction. You can also create your own custom variables
using policies like AssignMessage or in JavaScript, Node.js, and Java code. As you'll see, variables have scope,
and where they are accessible depends in part on when they are created in the API proxy flow. In general, when a
variable is created, it is available to policies and code that execute later in the API transaction flow.
Flow variable are used in policies and conditional flows. Policies can retrieve state from flow variables and use
them to do their work. For example, a VerifyAccessToken policy can retrieve the token to be verified from a flow
variable and then perform the verification on it. As another example, a JavaScript callout can retrieve flow
variables and encode the data contained within those variables. Conditional flows can reference flow variables to
direct the flow of an API through SAP API Management, kind of like the way a switch statement works in
Let's look at examples of how variables are used in each of these contexts.
Some policies take flow variables as input. For example, the following AssignMessage policy takes the value of the
flow variable client.ip and puts it in a request header called My-Client-IP. If added to the request flow, this policy
sets a header that is passed to the backend target. If set on the response flow, the header would be sent back to
the client app.
<AssignMessage name="set-ip-in-header">
<AssignTo createNew="false" transport="http" type="request">request</AssignTo>
<Set>
<Headers>
<Header name="My-Client-IP">{client.ip}</Header>
</Headers>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>
For another example, when a Quota policy executes, several flow variables are populated with policy-related
values. One of these variables is called ratelimit.my-quota-policy.used.count (where my-quota-
policy is the name of the quota policy you're interested in). You might later execute a conditional flow that says
"if the current quota count is below 50% of maximum, and it's between 9 am and 5 pm, enforce a different quota."
This condition might depend on the value of the current quota count and on a flow variable called system.time,
which is one of the built-in SAP API Management variables.
Conditional flows evaluate flow variables and enable proxies to behave dynamically. Conditions are typically used
to change the behavior of flows, steps, and route rules. Here's a conditional flow that evaluates the value of the
variable request.verb in a proxy flow step. In this case, if the request verb is POST, the VerifyApiKey policy is
executed. This is a common pattern used in API proxy configurations.
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>request.verb equals "POST"</Condition>
Using the JavaScript policy, you can execute JavaScript code from within the context of an API proxy flow.
JavaScript that is executed by this policy uses the SAP API Management JavaScript Object Model, which provides
your custom code access to request, response, and context objects associated with the API proxy flow in which
your code is executing. For example, this code sets a response header with the value obtained from the flow
variable target.name.
context.setVariable("response.header.X-SAP-Target",
context.getVariable("target.name"));
This techniqe of using JavaScript to read and set variables is similar to the work you can do with the
AssignMessage policy (shown previously). It's just another way to accomplish the same kinds of things on SAP
API Management. The key to remember is that JavaScript executed by the JavaScript policy has access to all the
flow variables that are exist and are in scope within the API proxy flow.
By requiring the SAP API Management-access module, you can set and access flow variables from within Node.js
code that is deployed to SAP API Management.
Here's a simple example where a variable called custom.foo is set to the value Bar. Once set, this new variable
becomes available to any policies or other code that occurs in the proxy flow after the Node.js code executes.
var http = require('http');
var sap = require('sap-access');
Variable scope is related to the flow or overall "life cycle" of an API proxy call.
To understand flow variable scope, it's important to understand or visualize the way messages flow through an
API proxy. An API proxy consists of a series or message processing steps organized as a flow. At every step in a
proxy flow, the proxy evaluates information available to it and decides what to do next. Along the way, the proxy
may execute policy code or perform conditional branching.
Keep this flow structure in mind as we begin to explore flow variables through the rest of this topic.
As soon as you can visualize how messages flow through a proxy, as described previously, you can begin to
understand variable scope. By scope, we mean the point in the proxy flow life cycle when a variable is first
instantiated. For example, if you have a policy attached to the ProxyEndpoint request segment, that policy will not
be able to access any variables that are scoped to the TargetEndpoint request segment. The reason for this is that
the TargetEndpoint request segment of the flow has not executed yet, so the API proxy hasn't had a chance to
populate variables in that scope.
The following table lists the complete set of variable scopes and indicates when in the proxy flow they become
available.
always available As soon as the proxy receives a request. These variables are
available through the entire proxy flow life cycle.
For example, there's a built-in SAP API Management variable called client.ip. This variable has "proxy request"
scope. It is automatically populated with the IP address of the client that called the proxy. It is populated when a
request first hits the ProxyEndpoint and remains available through the entire proxy flow life cycle.
There's another built-in variable called target.url. This variable's scope is "target request". It is populated in the
TargetEndpoint request segment with the request URL sent to the back-end target. If you try to
access target.url in the ProxyEndpoint request segment, you will receive a NULL value. If you try to set this
variable before it is in scope, the proxy does nothing—does not generate an error and does not set the variable.
Note
It's possible to configure some policies to either throw an error or return NULL when an undefined
variable is accessed. Refer to individual policy reference pages for details.
Here's a simple example that demonstrates how to think about variable scope. Suppose you want to copy the
entire contents of a request object (headers, parameters, body) and assign it to the response payload to be sent
back to the calling app. You can use the AssignMessage policy for this task. The policy code looks like this:
<AssignMessage name="CopyRequestToResponse">
<AssignTo type="response" createNew="false">response</AssignTo>
<Copy source="request"/>
</AssignMessage>
All built-in variables in SAP API Management follow a dot-notation naming convention. This convention makes it
easier to determine the purpose of the variable. For example system.time.hour and request.content.
Note
This dot-notation convention is strictly for naming purposes. For example, request.content does not
refer to a parent variable or object called "request". You can name custom variables anything you wish.
There is no requirement to include a dot. SAP API Management considers following this naming
convention a best practice whenever you create your own custom flow variables. It can be useful to use
the dots to organize your custom variables. For example approval.code and approval.status both
might refer to an approval feature within the flow. SAP API Management uses prefixes like request, target,
system, and response to organize relevant variables appropriately.
When you reference a variable in a policy, you must enclose it in curly braces. For example, this simple
AssignMessage policy takes the value of the variable client.ip and puts it in a request header called Client-
IP.
<AssignMessage name="set-ip-in-header">
<AssignTo createNew="false" transport="http" type="request">request</AssignTo>
<Set>
<Headers>
<Header name="Client-IP">{client.ip}</Header>
</Headers>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</AssignMessage>
In conditional flows, the curly braces are not necessary. For example, this condition evaluates the
variable request.header.accept.
<Step>
<Condition>request.header.accept = "application/json"</Condition>
<Name>XMLToJSON</Name>
</Step>
Flow variables have a well-defined data type, such as string, long, integer, boolean, and collection. You can find the
data types listed for each built-in SAP API Management flow variable in the Variables reference. For policy-created
variables, refer to the specific policy reference topic for data type information. Finally, variables you create
manually assume the type given when they were created, and depend on the types of values that are allowed. For
example, variables created in Node.js code are restricted to number, String, boolean, null, or undefined.
Many policies create flow variables as part of their normal execution. The Policy reference documents all of these
policy-specific variables. As you work with proxies and policies, be sure to consult the Policy reference to find out
which variables are created and what they are used for. For example, the Quota policy creates a set of variables,
that contain information about quota counts and limits, expiry time, and so on. See the section "Policy-specific
variables" in Quota policy for the complete list. Some policy variables are useful for debugging. You can use the
Trace tool, for instance, to see which variables were set at a particular instance in a proxy flow.
The ExtractVariables policy lets you populate custom variables with data extracted from messages. You can
extract query parameters, headers, and other data. For example, you can parse request and response messages
using patterns to extract specific data from the messages.
In this example, ExtractVariables is used to parse a response message and store specific data taken from the
response. Two custom variables are created and assigned values. The variables are
called geocoderesponse.latitude and geocoderesponse.longitude.
<ExtractVariables name="ParseGeocodingResponse">
<Source>response</Source>
<VariablePrefix>geocoderesponse</VariablePrefix>
<JSONPayload>
<Variable name="latitude">
<JSONPath>$.results[0].geometry.location.lat</JSONPath>
</Variable>
<Variable name="longitude">
<JSONPath>$.results[0].geometry.location.lng</JSONPath>
</Variable>
</JSONPayload>
</ExtractVariables>
Again, be aware that many policies automatically create variables. You can access those variables within the
proxy flow context, and they are documented in the Policy reference under each individual policy topic.
You can access and set variables directly in JavaScript code that is executing in the context of an API proxy.
Through the SAP API Management JavaScript Object Model, JavaScript executing on SAP API Management has
direct access to proxy flow variables.
To access variables in JavaScript code, call getter/setter methods on any of these objects:
• proxyRequest
• targetRequest
• targetResponse
• proxyResponse
• context
As you can see, these object references map to the familiar segments of the proxy flow model as explained
previously in "Visualizing the flow of an API proxy."
The context object corresponds to "globally" available variables, such as system variables. For example, you can
call getVariable() on the contextobject to get the current year:
var year = context.getVariable('system.time.year');
Similarly, you can call setVariable() to set the value of a custom variable or for any writable out-of-the-box
variables. Here, we create a custom variable called organization.name.myorg and assign a value to it.
Because this variable is created with the context object, it will be available to all flow segments (essentially, this is
like creating a global variable).
You can also get/set proxy flow variables in Java code that you execute with the JavaCallout policy.
You can get, set, and delete flow variables from Node.js code deployed to SAP API Management. All you need to
do is "require" the SAP API Management-access module in your code.
You can combine policies and resources into a shared flow that you can consume from multiple API proxies, and
even from other shared flows. Although it's like a proxy, a shared flow has no endpoint. It can be used only from an
API proxy or shared flow that's in the same organization as the shared flow itself.
By capturing in one place functionality that's useful in multiple places, a shared flow helps you ensure consistency,
shorten development time, and more easily manage code.
You can call a shared flow using the Flow Callout policy. Also, by attaching a shared flow to a flow hook, you can
have the shared flow execute before a proxy or target request, or after a proxy or target response.
For example, imagine you have areas of functionality that are either used in multiple places or must be
standardized across APIs in your organization. You could have a shared flow for each category, including:
• security, with authorization code using OAuth and API key verification, as well as threat protection code.
• logging, for generating standard error messages.
• mediation, for transforming between XML and JSON message formats.
In the following illustration, two API proxies call out (with a FlowCallout policy) to a shared flow to authenticate
incoming user requests. The AuthSharedFlow has been deployed separately to the org before the proxies so that
it is available to support requests from the proxies. A shared flow can be developed and managed by a team
responsible for broad company policies, then consumed in proxies by line-of-business teams building more
specialized apps.
When developing a shared flow, you must always test it with calls sent to an API proxy. In other words, you can't
send requests directly to a shared flow as you would an API proxy. Instead, you send requests to an API proxy
which is, in turn, calling out to the shared flow.
2. Develop a shared flow by implementing policies and supporting resources, just as you would when
developing an API proxy.
A shared flow is a sequence of conditional steps. So developing one is like developing an API proxy. You can
include policies and resources you might include in a proxy.
For example, as part of your traffic management support, you might implement a Spike Arrest policy to allow
only 30 requests per second, as in the following example:
<SpikeArrest async="false" continueOnError="false" enabled="true" name="Spike-
Arrest">
<DisplayName>Spike Arrest</DisplayName>
<Properties/>
<Identifier ref="request.header.some-header-name"/>
<MessageWeight ref="request.header.weight"/>
<Rate>30ps</Rate>
</SpikeArrest>
Then, to a shared flow for traffic management, you could attach the Spike Arrest policy as a step. The policy
would execute for any API proxy that calls the shared flow.
<SharedFlow name="default">
<Step>
<Name>Spike-Arrest</Name>
</Step>
</SharedFlow>
As with API proxies, you can import a zip file containing your shared flow source artifacts (see Import a new
API Proxy for more about importing proxies). The following illustrates how to import a shared flow with
the management API:
curl -X POST -F "file=@/path/to/zip/file.zip" \
'https://api.enterprise.apigee.com/v1/o/{org_name}/sharedflows?action=import&nam
e=shared-flow-name' \
-u email:password
You can deploy a shared flow with a management API call such as the following:
curl -X POST --header "Content-Type: application/octet-stream" \
https://api.enterprise.apigee.com/v1/o/{org_name}/e/{env_name}/sharedflows/{shared_
flow_name}/revisions/{revision_number}/deployments \
-u email:password
You can also replace a currently deployed shared flow with no downtime.
Here's the request form using the management API:
curl -X POST --header "Content-Type:application/x-www-form-urlencoded" \
https://api.enterprise.apigee.com/v1/o/{org_name}/e/{env_name}/sharedflows/{shared_
flow_name}/revisions/{revision_number}/deployments?"override=true" \
-u email:password
4. Develop the consuming API proxy so that it can call the shared flow as part of its own flow.
From an API proxy, you call to a shared flow with a Flow Callout policy.
Note: To consume a shared flow, an API proxy must be deployed after the shared flow and to the same
environment as the shared flow. The shared flow has to be in place when you want to test a call to it using the
Flow Callout policy.
To consume a shared flow, you add a Flow Callout policy to the proxy or shared flow that will consume it. Like
a Service Callout policy, with which you call out to another service, a Flow Callout calls out to the shared flow.
In the following code, a Flow Callout policy calls out to a shared flow called traffic-management-shared.
<FlowCallout async="false" continueOnError="false" enabled="true" name="Traffic-
Management-Flow-Callout">
<DisplayName>Traffic Management Flow Callout</DisplayName>
<Properties/>
<SharedFlowBundle>traffic-management-shared</SharedFlowBundle>
</FlowCallout>
5. Deploy the consuming API proxy to begin using the shared flow.
6. Develop iteratively by tracing, as you would with an API proxy.
As with an API proxy, you develop a shared flow by iteratively invoking and tracing until you have the logic the
way you want it. In this case, because the shared flow doesn't run on its own, you invoke a proxy endpoint and
trace the proxy.
Here are the steps:
1. Make sure that both the shared flow and the API proxy calling it with a Flow Callout policy are in the same
organization and deployed to the same environment.
When you use the SAP API Management Edge UI to create a shared flow, you can either create one from scratch
or by importing existing flow sources as a flow bundle .zip file.
1. In the management console, select the organization within which you want to create the shared flow.
The shared flow will be available to any API proxies and shared flows deployed to an environment from this
organization. It won't be available from outside this organization.
2. Click the APIs > Shared Flows menu.
On the Shared Flows page, you can view a list of shared flows in the organization. You can edit or delete flows
in the list.
3. Click the + Shared Flow button to begin adding a new shared flow.
4. On the Build a Shared Flow page, choose how you want to created the new flow:
o Create a new flow from scratch. You'll be able to configure policies and resources as steps in the flow.
1. Select Empty Shared Flow.
2. Enter a name value. This will be the name that API proxies and other shared flows use to reference
this shared flow. The name should be descriptive to developers consuming the flow.
3. Enter a description to provide more information about what the flow does.
4. Click Next.
5. Optionally, select the environments to which you want the new flow deployed.
For example, if you'll be testing the shared flow from API proxies deployed to the test environment,
then deploy the shared flow to test.
6. Click Build and Deploy to have the new shared flow created and deployed to the environment(s) you
selected. If you selected no environment, the shared flow will be created, but not deployed.
You can call a shared flow from a proxy or from another shared flow by using the Flow Callout policy.
1. In the SAP API Management Edge management console, locate the proxy or shared flow from which you want
to call another shared flow.
2. In the Navigator, next to Policies, click the + button.
3. In the list of policies, under Extension, click Flow Callout.
4. Enter the display name and name (unique identifier), then select the shared flow that this policy will call.
5. Click Add.
6. Add the new Flow Callout policy to the proxy where you want the call to be made.
SAP API Management enables you to 'program' API behavior without writing any code, by using 'policies'. A policy
is like a module that implements a specific, limited management function. Policies are designed to let you add
common types of management capabilities to an API easily and reliably. Policies provide features like security,
rate-limiting, transformation, and mediation capabilities, saving you from having to code and maintain this
functionality on your own.
You're not limited to the set of policy types provided by SAP API Management. You can also write custom scripts
and code (such as JavaScript), that extend API proxy functionality and enable you to innovate on top of the basic
management capabilities supported by SAP API Management Policies
Policy Types
Technically, a policy is an XML-formatted configuration file. Each policy type's structure (for example, the
required and optional configuration elements) is defined by an XML schema. SAP API Management Policy types
are grouped into the following functional categories:
Traffic Management
Policies in the traffic management category enable you to control the flow of request and response messages
through an API proxy. These policies support both operational and business-level control. They give you control
over raw throughput, and can also control traffic on a per-app basis. Traffic management policy types enable you
to enforce quotas, and they also help you to mitigate denial of service attacks.
Mediation
Policies in the mediation category enable you to actively manipulate messages as they flow through API proxies.
They enable you to transform message formats, from XML to JSON (and vice-versa), or to transform one XML
Security
Policies in the security category support authentication, authorization, as well as content-based security.
Extension
Policies in the extension category enable you to tap into the extensibility of API Platform to implement custom
behavior in the programming language of your choice.
Each Policy type is documented in detail in the Policy Section. This topic demonstrates general interaction,
showing you how to create Policies, and how to attach them to Flows in an API proxy configuration.
One type of policy that is commonly used is SpikeArrest. SpikeArrest prevents sudden increases in message
traffic that might swamp your backend services.
3. Select the policy type that you want to add to the API proxy.
For example, if you want to add a SpikeArrest policy, select the Traffic Management category in the policy
dropdown menu.
4. Modify the selections in the New Policy dialog to configure and attach the policy.
If you accept the default selections, as shown below, the policy will be enforced on request messages
submitted by client apps to the ProxyEndpoint PreFlow.
Configuring Policies
When the UI generates a policy instance, it applies reasonable default values for common settings. You may need
to modify these settings to meet your requirements.
Example
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<SpikeArrest async="false" continueOnError="false" enabled="true"
name="spikearrest-1">
<DisplayName>SpikeArrest-1</DisplayName>
<FaultRules/>
<Properties/>
<Identifier ref="request.header.some-header-name"/>
<MessageWeight ref="request.header.weight"/>
<Rate>30ps</Rate>
</SpikeArrest>
You can configure a policy by directly editing its XML configuration in the Code view. For example, the peak
message rate for the Spike Arrest policy is initially set to 30 messages per second. You can change the peak rate
by changing the <Rate> element value in the XML for the policy.
You can also cut-and-paste policies into the Code view.
When you make changes to a policy definition in the Code view, the changes are reflected in the Property
Inspector. The reverse is also true — make changes in the Property Inspector and they appear in the XML in
the Code view.
Some policies expose XML elements that can have multiple subelements. For example, the AssignMessage policy
(which is used in the request or response path to generate a new message or to modify an existing message)
exposes various elements in which multiple query parameters can be specified. In these cases, the Property
Inspector displays a (+) icon. Choose the icon to add entry fields for additional subelements.
You can create and edit Policies locally, using your favorite text or XML-aware editor or IDE. This topic uses the
Quota policy type as an example of how to create, configure, attach, deploy, and test policies.
Most API proxies enforce a quota. Quotas provide control over how often a client app is permitted to invoke an API
over a given time interval. In the example below, a Quota policy is configured to limit apps to 1 request per minute.
(While this may not be realistic, it does provide a simple way to see the effects of a policy.)
In an API proxy configuration, Policy files are stored as XML files under /apiproxy/policies directory.
For example, a policy of type Quota called "QuotaPolicy" could be created as a file called QuotaPolicy.xml with the
following content:
<Quota enabled="true" continueOnError="false"
async="false" name="QuotaPolicy">
<Allow count="1"/>
<Interval>1</Interval>
<TimeUnit>minute</TimeUnit>
</Quota>
You can create a text file by hand, or you can generate the policy from an XML schema. All policies have some
settings that are specific to the policy type, and some settings that are generic across all policies.
When you attach policies in the management UI, the API proxy builder generates the policy instance from the XML
schema for the policy type you selected. Therefore, you may see elements in the policy configuration that, for
clarity, are not always included in documentation.
All policies define the following attributes:
• enabled: Indicates whether the policy is turned "on" or "off". Policies can be enabled/disabled at runtime by
changing this setting. A policy that has enabled set to false is not enforced.
• continueOnError: Defines whether the pipeline should continue processing the message if the policy fails.
When enforcing quota policies, errors likely indicate that the quota has been exceeded, and, therefore, this
attribute should be set to false.
• async: In a policy, enabling async=true tells API Plarform to run the policy inside a different thread pool,
isolated from the regular pool that is servicing the request/response Flow. This is an internal optimization that
will rarely be of use to API developers.
• name: The name that you give to this policy. This name is unique to this policy instance, and it is used to
attach the policy to the flow as a processing step.
Policies are not executed until they are attached to a Flow. You can create a Policy attachment by naming a Policy
in a Step configuration.
The choice of attachment point is critical to the behavior of your API proxy. For example, if you attach the Quota
policy to a response Flow, then the Quota would be enforced after the request message was sent to the backend
service. That would defeat the purpose of applying a Quota policy! Therefore, you need to attach the Quota policy
as a processing Step on the request Flow.
The format of a policy attachment is:
<Step>
<Name>{policy_name}</Name>
</Step>
Example
<Step>
<Name>QuotaPolicy</Name>
</Step>
Recommendation
The {policy_name} variable must be the same as the name attribute in the policy (stored under /policies)
that you want to attach. The names must match exactly, as name matching is case-sensitive.
A policy is attached to a Flow by adding the Step configuration to the appropriate request or response Flow
element in a ProxyEndpoint or TargetEndpoint configuration.
You can attach a policy to a request or response Flow. Request and response Flows are further subdivided in
to PreFlow and PostFlow.
The following example demonstrates the minimal ProxyEndpoint configuration, with no policy attachments. It
simply defines the (inbound) HTTPProxyConnection and a RouteRule.
<ProxyEndpoint name="default">
<HTTPProxyConnection>
<BasePath>/weather</BasePath>
<VirtualHost>default</VirtualHost>
</HTTPProxyConnection>
The rest of the ProxyEndpoint configuration remains the same. The only change is that you added the
PreFlow, Request, and Step elements. In the ProxyEndpoint configuration above, the Quota policy executes
Recommendation
You can also define conditional Flows that execute between the PreFlow and PostFlow phases. This is
covered in the next topic, Flow Variables and Conditions.
For policy changes to take effect, you must deploy the API proxy revision to an environment. After you attach a
policy or make changes to an existing policy, use the management UI or the management API to deploy the
changes.
To verify that a policy is enforced properly, the API must be invoked by an HTTP client. To verify this Quota
configuration, submit multiple requests to the API, exceeding the quota limit that you set in the quota policy. (The
URI path, configured as the base path setting in the ProxyEndpoint, in the request below is /weather).
http://<host:port>/weather/forecastrss?w=12797282
After you submit more than 1 request within a minute, you should see the following error message:
{"fault":{"faultstring":"policies.ratelimit.QuotaViolation","detail":{"errorcode":"pol
icies.ratelimit.QuotaViolation"}}}
This indicates that the Quota policy is being enforced by API Platform.
Note the format of the error message above. It contains a faultstring property and an errorcode property. In many
cases, you need to implement some behavior to handle these errors. For example, you may wish to issue a
customized message to a developer whose app has exceeded the Quota.
To do so, you use the FaultRule element on the Step. A FaultRule element can be attached to any policy. The
behavior of the FaultRule is defined by the Policy that you attach to the FaultRule.
Example
<Step>
<FaultRules>
<FaultRule>
<Name>QuotaLimitAlertPolicy</Name>
<Condition>(fault.name = ratelimit.QuotaLimitCheck.exceed.count)</Condition>
<FaultRule>
To meet basic management requirements, API proxies usually enforce the following policies:
Request Flow:
1. SpikeArrest
2. JSONThreatProtection
3. API key validation
4. Quota
5. JSONToXML
Response Flow:
1. XMLToJSON
2. ResponseCache
SpikeArrest
This policy smooths traffic spikes by dividing a limit that you define into intervals of 10 milliseconds. For example,
if you define a limit of 100 messages per second, the SpikeArrest policy enforces a limit of around 10 per
millisecond. The SpikeArrest limit should be close to capacity calculated for either your backend service or the API
proxy itself. The limit should also be configured for shorter time intervals, such as seconds or minutes. This policy
should be used to prevent sudden traffic bursts caused by malicious attackers attempting to disrupt a service
using a denial-of-service (DOS) attack or by buggy client applications.
See Shield APIs using SpikeArrest section in the Policy document.
Quota
This policy enforces consumption limits on client apps by maintaining a distributed 'counter' that tallies incoming
requests. The counter can tally API calls for any identifiable entity, including apps, developers, API keys, access
tokens, and so on. Usually, API keys are used to identify client apps. This policy is computationally expensive so,
for high-traffic APIs, it should be configured for longer time intervals, such as a day or month. This policy should
be used to enforce business contracts or SLAs with developers and partners, rather than for operational traffic
management.
See Rate limit API traffic using Quota section in the Policy document.
This policy enables traffic management between API Platform and your backend services. Some backend
services, such as legacy applications, may have strict limits on the number of simultaneous connections they can
support. This Policy enforces a limit on the number of requests that can be sent at any given time from API
Platform to your backend service. This number is counted across all of the distributed instances of API Platform
that may be calling your backend service. Policy limits and time duration should be configured to match the
capacity available for your backend service.
See Throttle backend connections using ConcurrentRatelimit in the Policy document.
Introduction
API proxies that run on API Platform are stateless. They enforce policies and execute scripts and code, but the
environment in which they run is populated with context that is specific to each request/response transaction.
To provide API proxies with access to data over multiple transactions, API Platform provides a persistence layer
that enables API proxies to store data. The persistence layer consists of L1 and L2 caches and a NoSQL key/value
store. These caches and the data store work together to optimize availability and performance.
As a developer, you can access this persistence layer without knowing the details of its implementation. Instead,
you use a set of policies to interact with the persistence layer at runtime. API Platform defines three policy types
that enable you to configure persistence for API proxies using configuration instead of code.
SAP API Management supports these persistence scenarios:
• A cache for serving duplicates of stored static response messages
• A general purpose caching mechanism for persisting any arbitrary objects used by your API proxies
• HTTP/1.1 compliant caching
• A highly performant NoSQL key/value store for simple data sets used by your API proxies
Response Cache
Response caching is a dedicated application of the API Platform caching mechanism. Response caching is
implemented in the ResponseCache policy, so enabling ResponseCaching for your APIs requires no coding on
your part.
Not all data is updated in real-time. Services often only update data periodically, for example, weather data
updates every 10 minutes, or product catalog prices update every 24 hours.
When ResponseCache is employed in a proxy, SAP API Management also looks at certain HTTP response caching
headers and takes appropriate actions according to the directives of those headers. For example, on responses
from backend targets, SAP API Management supports the Cache-Control header, which can be used to control
the maximum age of a cached response, among other directives. For more information, see HTTP response
caching.
A consideration for response caching is that responses larger than 256KB are not distributed across the SAP API
Management infrastructure. This is done to optimize performance.
Cache
Caching is more general purpose than ResponseCache, enabling you to persist any object that your API proxies
require over multiple request/response sessions. API Platform provides policies for populating, retrieving, and
flushing the cache at runtime. The interaction mechanism that links the API proxies with the underlying cache is
variables. You can use policies or code in your API proxies to populate and retrieve cached objects by interacting
SAP API Management supports a subset of HTTP/1.1 compliant cache headers, including the cache-control
header and entity tags. For more information, see HTTP response caching.
Key/value Map
If the data you need to store is structured or is long-lived, then use the key/value map.
Examples of situations where you would use the key/value store are:
• A map of IP addresses to country codes
• A list of IP addresses for whitelisting/blacklisting
• A mapping of long URLs to corresponding shortened URLs
API Platform provides a set of policies for interacting with the key/value store at runtime. It also exposes a
RESTful API for managing the contents of the key/value store. The API enables you, for example, to perform bulk
operations to populate the key/value store with large data sets.
Therefore, key/value maps work better for single entities that have many properties. For example:
curl -H "Content-Type:application/json" -X POST -d \
'{
"entry" : [ {
"name" : "development",
"value" : "dev.apifactory.com"
}, {
"name" : "production",
"value" : "prod.apifactory.com" } ],
"name" : "URLs"
}' \
http://<host:port>/v1/o/{org_name}/keyvaluemaps \
-u myname:mypass
The result is a key/value map that can be retrieved as JSON or XML for use at runtime by policies or code that you
write.
You can add entries to the key/value map by using the PUT verb. You only need to include the entries to be added:
curl -H "Content-Type:application/json" -X PUT -d \
The PopulateCache policy does not persist cache entries. Entries are in memory until the configured expiration
time. You can look up the value only until it expires. One limitation is that you cannot find the list of keys that are
currently in a cache.
When using KeyValueMap, the keys are persisted indefinitely. There are APIs available to retrieve the list of keys.
There is no expiration time for the keys; you must explicitly delete them.
The HTTP/1.1 specification describes standard caching headers and control mechanisms that support caching
along the HTTP request/response chain. These headers and mechanisms provide information about cached
resources and help servers determine how to manage cached data. You can refer to the spec itself for detailed
information about caching in HTTP, and there are also many blogs, articles, and other resources available on the
internet that explains HTTP caching.
The focus of this topic is to explain how SAP API Management processes and handles HTTP/1.1 headers related to
response caching.
Recommendation
SAP API Management currently supports a subset of the HTTP/1.1 caching headers and directives. Where
appropriate, we'll point out features that are not supported.
SAP API Management provides a persistence layer that allows HTTP responses and arbitrary variables to be
stored in caches. You enable and control this persistence layer with policies. SAP API Management provides
policies for storing arbitrary variables (the Cache policies) and a policy for controlling HTTP response caching (the
ResponseCache policy).
You can read an overview of the SAP API Management persistence layer in Persistence.
Recommendation
SAP API Management Platform does not perform any caching unless one or more of these policies are
attached to a proxy.
This topic concerns HTTP response caching and how the HTTP/1.1 caching headers are handled when the
ResponseCache policy is employed by a proxy. To learn about adding and configuring the ResponseCache policy,
see Reduce latency using ResponseCache.
When the ResponseCache policy is added to a proxy, HTTP responses are cached and retrieved according to how
the proxy is configured. The ResponseCache policy includes two flag elements that, when set, allow the policy to
consider HTTP cache headers. If you want to use these HTTP cache header features, you need to set these flag
elements. They are:
o UseResponseCacheHeaders: If set to true, the HTTP response headers are used when setting the "time
to live" (TTL) of the response in the cache. The Expires response header is ignored by default unless this
flag is set to true. If the max-age or s-maxage directives of the Cache-Control header are set, they take
precedence over the Expires header value.
o UseAcceptHeader: When this flag is set to true, the Accept headers in the response are used to generate
a cache key. The default is false. See "How are cache keys generated".
In addition, SAP API Management looks for and evaluates certain HTTP caching headers. SAP API
Management also considers these headers and takes appropriate action based on their directives. In some
cases, these HTTP/1.1 cache headers override whatever behavior is specified in the ResponseCache policy.
For example, if the Cache-Control header is returned from a backend server, the header's s-
maxage directive overrides the corresponding setting in the ResponseCache policy.
SAP API Management supports the following HTTP cache headers on responses received from backend
target (origin) servers:
o Cache-Control
o Expires
On client GET requests, SAP API Management supports the The If-Modified-Since header.
SAP API Management also supports Entity Tags (ETags) and their related GET request headers.
o If-Match
o If-None-Match
Finally, SAP API Management provides support for caching and returning compressed responses.
This section discusses SAP API Management support for the Cache-Control header.
Recommendation
Although the HTTP/1.1 spec allows Cache-Control headers in both client requests and origin server
responses, SAP API Management only supports the Cache-Control header on responses returned from
origin servers (backend targets). Origin servers can include both target endpoints defined in an e SAP API
Management API proxy and those created using TargetServer API calls.
When SAP API Management detects a Cache-Control response header, it looks at the header's directives and
takes appropriate processing steps.
SAP API Management supports a subset of Cache-Control response header capabilities defined in the HTTP/1.1
specification. Please note the following:
SAP API Management does not support Cache-Control headers that arrive with inbound client requests.
According to the HTTP specification, Cache-Control can either be public (shared) or private (single user).
However, SAP API Management only supports the notion of public caches.
Not all Cache-Control response directives in the HTTP/1.1 specification are supported by SAP API Management.
See "Support for Cache-Control response header directives" below for details.
The following table describes SAP API Management support for HTTP Cache-Control response header directives.
Recommendation
SAP API Management supports subset directives from the HTTP/1.1 specification on responses from
origin servers. For more detailed information on these directives, see "Cache-Control" in the HTTP/1.1
specification.
SAP API Management uses the Expires header on origin server responses to determine the time to live (TTL)
of a cached entry. As expected, this header specifies a date/time after which a response's cache entry is
considered stale. This header allows servers to signal when it's okay to return a cached value based on a time
stamp.
An entity tag (ETag) is an identifier associated with a requested resource. This identifier allows servers to
determine if the requested resource and the associated cached resource match or not. Servers can then take
appropriate actions, such as re-caching a response if it does not match or returning the cached resource if the
ETags match. When a target endpoint sends a response back to SAP API Management with an ETag, SAP API
Management caches the ETag along with the response. You can read more about Entity Tags in "Protocol
Parameters" in the HTTP/1.1 specification.
The If-Match request header allows SAP API Management to determine if a cached entity is current or not based
on if the ETag in the header matches the ETag that is cached with the requested entity. You can read more
about If-Match in "Header Field Definitions" in the HTTP/1.1 specification.
If SAP API Management receives an inbound GET request from a client that includes an If-Match header:
o If the If-Match header specifies one or more ETags, SAP API Management retrieves any unexpired cached
entries for the specified resource and compares any strong ETags on those cached entries with those
specified in the If-Match header. If a match is found, the cached entry is returned. If not, the request is
passed to the origin server.
o If the If-Match header specifies "*", the request is passed on to the origin server to ensure that any origin
caching facilities have a chance to process the request.
o Any requests other than GET that specify an If-Match header are passed on to the origin server to ensure
that any origin caching facilities have a chance to process the request.
o If a cache entry with the same request URI is found, but it contains only weak ETags, then the entry must
be revalidated by the origin server before being returned to the client.
o Any ETags returned by the origin server are returned unchanged to the client.
The If-None-Match header allows SAP API Management to determine if a cached entity is current or not based on
if the ETag in the header does not match the ETag that is cached with the requested entity.
If SAP API Management receives an inbound GET request from a client that includes an If-None-Match header:
o If the If-None-Match header specifies one or more ETags, SAP API Management retrieves any
unexpired cache entries for the specified URI and compares any strong ETags on those cached entries
with those specified in the If-None-Match header. If a match is found, SAP API Management returns a 304
Not Modified status. If no match is found, SAP API Management passes the request to the origin server.
o If the If-None-Match header specifies "*" and an unexpired cached entry for the requested URI exists,
SAP API Management returns a 304 Not Modified status.
o Requests other than a GET that include an If-None-Match header are passed on to the origin server.
o If a cache entry with the same request URI is found but contains only weak ETags, then the entry must be
revalidated by the origin server before SAP API Management returns it to the client.
o If SAP API Management receives an ETag from an origin server, the ETag is always returned unchanged
to the client.
If SAP API Management receives an If-Modified-Since header in a GET request, it is passed along to the origin
server even if a valid cache entry exists. This ensures that any updates to a resource that did not pass through
SAP API Management are accounted for. If the origin server returns a new entity, then SAP API Management
replaces the existing cache entry with the new value. If the server returns a 304 Not Modified status, SAP API
Management returns the response value if the cached response's Last-Modified header indicates that it has not
changed.
When an incoming request includes the header Accept-Encoding with values of gzip, deflate or compress,
the origin server responds with compressed data. When subsequent responses come without the Accept-
Encoding headers, they expect an uncompressed response. SAP API Management's response caching
mechanism is capable of sending both compressed and uncompressed responses depending on the incoming
headers without going back to the origin server.
When the ResponseCache flag UseAcceptHeader is set to true, SAP API Management uses the Accept, Accept-
Encoding, Accept-Language and Accept-Charset request headers when calculating the cache key. This
approach prevents a client from getting a media type they did not ask for. For example, consider if two requests
come in from the same URL, where the first request accepts gzip and the second does not. The first request will
be cached, and the cached entry will (probably) be a gzipped response. The second request will read the cached
value and may then return a gzipped entry to a client that is not capable of reading gzip.
By default, SAP API Management only caches 2xx level responses. Non-2xx responses are not cached.
Fault Handling
Many error conditions can arise while API proxies are servicing requests from apps. For example, API proxies may
encounter network issues when communicating with backend services, apps may present expired credentials,
request messages may be incorrectly formatted, and so on. In many cases, you will need to handle such errors in
a customized fashion. This topic shows you how to set up custom fault handling using the controls provided by
API Platform.
About Errors
When an API proxy encounters an error, the default behavior of the API proxy is to exit the normal processing
pipeline, meaning exit the current flow, and to enter an Error flow. Once the API proxy enters the Error flow, it
cannot return processing back to the normal flow pipeline.
By entering the Error flow, the proxy:
• Bypasses any remaining processing steps, meaning any remaining policies, in the current flow
• Bypasses any subsequent flows
• Returns a fault response to the requesting app.
This process results in a raw error message or error codes being returned to the requesting app.
For all errors other than policy errors, an API proxy immediately enters the Error flow. For policy errors, meaning
failures arising while processing a policy, the continueOnError element of a policy controls the way the API
proxy reacts to an error.
By default, the continueOnError element is false, meaning that when a fault occurs in a policy, control is
directed to the Error flow. For example, the following VerifyAPIKey policy uses the default value of
the continueOnError element:
<VerifyAPIKey async="false" continueOnError="false" enabled="true" name="verify-api-
key">
<DisplayName>Verify API Key</DisplayName>
<APIKey ref="request.queryparam.apikey"/>
</VerifyAPIKey>
If you set the continueOnError element to true, control stays in the current flow of the API proxy and the next
policy in the pipeline executes.
In many cases you want to control the response of your API proxy to an error. For example, you might want to
send a custom error message when a developer app exceeds a Quota, add more information about the error to
the response, remove information from the response not meant to be seen by the calling app, or to modify the
response in other ways to improve usability and security.
SAP API Management enables you to customize error handling by defining fault rules. A fault rule specifies two
items:
• A Condition that specifies the fault to be handled based on the pre-defined category, subcategory, or name of
the fault
• One or more policies that define the behavior of the fault rule for the corresponding Condition.
Hint
To add a fault rule you need to edit the XML configuration of the ProxyEndpoint or TargetEndpoint. You
can use the SAP API Management UI to make this edit in the Code pane of the Develop view for an API
proxy, or edit the XML file that defines the ProxyEndpoint or TargetEndpoint.
<FaultRule>
...
</FaultRule>
</FaultRules>
OR
<FaultRules>
<FaultRule>
<Step>
<Name>{policy_name}</Name>
<Condition>{(conditional statement)}</Condition>
</Step>
</FaultRule>
<FaultRule>
...
</FaultRule>
where the Condition applies to the entire fault rule or only to a specific step in the fault rule. You can define
multiple fault rules in a ProxyEndpoint or TargetEndpoint to handle multiple fault conditions.
When a FaultRule's condition evaluates to true, then the Policy named in the FaultRule will execute and any
subsequent policies with matching conditions will execute. This is different behavior from Route Rules and
Flow conditions which stop once a condition is met. In those cases, even if environment conditions match
subsequent Route Rules and Flow conditions, those Route Rules and Flows will be ignored.
Recommendation
You can learn how to configure conditions by referring to the topic Flow Variables and Conditions.
Each type of error defines a set of error codes that it creates in response to an error. For policy errors, you can
find the error codes for each policy in the policy reference, starting with the Policy Reference.
All policy error codes have the same format, as shown in the example below:
{
"code" : " {error.code} ",
"message" : " {Error message} ",
"contexts" : [ ]
}
For example, when a developer app presents and invalid consumer key, the VerifyApiKey policy returns the
following error code:
{
"code" : " InvalidApiKey ",
"message" : "The consumer key presented by the app is invalid.",
"contexts" : [ ]
}
Use the error code to define the condition the defines the fault rule to execute. The fault.name variable contains
the value of the code field of the error code. You then use the fault.name variable in the <Condition> tag, as the
following example shows:
<ProxyEndpoint name="default">
...
<FaultRules>
<FaultRule name="invalid_key_rule">
<Step>
<Name>{policy_name}</Name>
</Step>
Note
If multiple fault rules have a condition that evaluates to true, then the last of those fault rules executes.
Now that you have configured a fault rule, you need to add a policy to the rule to handle the error. This policy then
determines the action of the fault rule.
While you can put any policy in the fault rule, you commonly use the Raise Fault policy. Use the RaiseFault policy
to generates a custom response message for an error condition. RaiseFault enables you to configure an HTTP
response with payload, HTTP status code, headers, and reason phrase elements.
Note
A policy used in a fault rule is typically not used in the normal flow pipeline. However, when using the SAP
API Management UI to create a policy, the SAP API Management UI by default assigns the policy to a flow.
For example, it can assign it to the Flow PreFlow, ProxyEndpoint default. Therefore, when using the SAP
API Management UI to create a policy for a fault rule, you typically uncheck the Attach Policy checkbox,
as shown below, so that the policy is not assigned to a flow:
You can now use this policy in your fault rule. Notice how you reference the RaiseFault policy by name in the fault
rule:
<ProxyEndpoint name="default">
...
<FaultRules>
<FaultRule name="invalid_key_rule">
<Step>
<Name>fault_invalidkey</Name>
</Step>
<Condition>(fault.name = "InvalidApiKey")</Condition>
</FaultRule>
</FaultRules>
You can execute multiple policies in a fault rule, as the following example shows:
<ProxyEndpoint name="default">
...
<FaultRules>
<FaultRule name="invalid_key_rule">
<Step>
<Name>policy1</Name>
</Step>
<Step>
<Name>policy2</Name>
</Step>
<Step>
<Name>policy3</Name>
</Step>
<Condition>(fault.name = "InvalidApiKey")</Condition>
</FaultRule>
</FaultRules>
</ProxyEndpoint>
The policies execute in the order defined. For example, you can use the Message Logging policy, the Extract
Variables policy, the AssignMessage policy, or any other policy in the fault rule. Note that processing of the fault
rule stops immediately if either of these situations occur:
• Any policy in the fault rule causes an error
• Any of the policies in the fault rule is of type RaiseFault
As a best practice, you should define a rules that determine the error responses from your APIs. In that way, you
deliver consistent and helpful information your clients.
The example Raise Fault policy below uses the <Payload>, <StatusCode>, and <ReasonPhase> tags to define
the custom error response sent back to the client:
<RaiseFault name="fault_invalidkey">
<FaultResponse>
<Set>
The DefaultFaultRule acts an exception handler for any error that is not explicitly handled by a FaultRule. If no
FaultRules are configured in an API proxy, then the DefaultFaultRule will handle all faults that occur. Default fault
handling can be enabled by configuring DefaultFaultRule as a child element of a ProxyEndpoint or a
TargetEndpoint.
The TargetEndpoint configuration below is configured with a DefaultFaultRule. The FaultRule indicates that when
an error condition is encountered during message processing, a policy called ReturnError executes.
<TargetEndpoint name="default">
<DefaultFaultRule name="fault-rule">
<Step>
<Name>ReturnError</Name>
</Step>
</DefaultFaultRule>
<HTTPTargetConnection>
<URL>http://weather.yahooapis.com</URL>
</HTTPTargetConnection>
</TargetEndpoint>
DefaultFaultRule is typically used to return a generic error message for any unexpected error. For example,
you might configure the DefaultFaultRule to return a message that contains support contact information. This
Recommendation
Set the flag AlwaysEnforce to true on DefaultFaultRule. This enables the DefaultFaultRule to process any
faults captured by more specific FaultRules. In this case, you can customize the error response (by
adding an HTTP header, for example) on the ProxyEndpoint.
An example of a simple Policy that you might use with a DefaultFaultRule is shown below. The policy is of type
AssignMessage, and generates a simple text response for any predefined error condition:
<AssignMessage name="ReturnError">
<Set>
<Payload type="text/plain">SERVICE UNAVAILABLE. PLEASE CONTACT SUPPORT:
[email protected].</Payload>
</Set>
</AssignMessage>
Include the <AlwaysEnforce> element in the <DefaultFaultRule> tag to execute the default fault rule for
every error, even if another fault rule has already been executed. The default fault rule is always the last fault rule
to execute:
<DefaultFaultRule name="fault-rule">
<Step>
<Name>ReturnGenericError</Name>
</Step>
<AlwaysEnforce>true</AlwaysEnforce>
</DefaultFaultRule>
One use of the default fault rule is to determine the type of error that occurs when you otherwise cannot
determine it. For example, your API proxy is failing for an error that you cannot determine. Use the default fault
The examples shown so far all use a fault rule on the ProxyEndpoint or TargetEndpoint to handle any policy errors
as part of the Error flow. That is because the default value of the continueOnError element of a policy is false,
meaning that when an error occurs in a policy, control is directed to the Error flow. Once in the Error flow, you
cannot return control back to the normal pipeline and you typically return some form of error message to the
calling app.
However, if you set the continueOnError element to true for a policy, control stays in the current flow and the
next policy in the pipeline executes after the policy that caused the error. The advantage to handling the error in
the current flow is that you might have a way to recover from the error to complete processing of the request.
Shown below is a VerifyAPIKey policy named verify-api-key with the continueOnError element set to true:
<VerifyAPIKey async="false" continueOnError="true" enabled="true" name="verify-api-
key">
<DisplayName>Verify API Key</DisplayName>
<APIKey ref="request.queryparam.apikey"/>
</VerifyAPIKey>
If the API key is missing or invalid, then the VerifyAPIKey policy sets the verifyapikey.verify-api-key.failed variable
to true, but processing continues in the current flow.
You then add VerifyAPIKey policy as a step in the PreFlow of the ProxyEndpoint:
Notice how the next step in the PreFlow uses a condition to test for the existence of an error. If an error occurred
in the VerifAPIKey policy, then the policy named FaultInFlow policy executes. Otherwise, the FaultInFlow policy is
skipped. The FaultInFlow policy can do many things, such as logging the error, attempting to fix the error, or
performing some other action.
You can use the RaiseFault policy at any time in a flow to trigger an error. When a RaiseFault policy executes, it
terminates the current flow and transfers control to the Error flow.
One use of the RaiseFault policy is to test for a specific condition that another policy might not detect. In the
example above, you added a <Condition> tag to a PreFlow <Step> tag that caused the policy FaultInFlow to
execute if the condition is met. If FaultInFlow is a RaiseFault policy, then control transfers to the Error flow. Or, you
might insert a RaiseFault policy in a flow to debug and test your fault rules.
When a RaiseFault policy triggers an error, you can use the following fault rule and condition to process it:
<FaultRule name="raisefault_rule">
<Step>
<Name>{policy_name}</Name>
</Step>
<Condition>(fault.name = "RaiseFault")</Condition>
</FaultRule>
The configuration shown in the previous section works for application-level errors. To return custom responses
for transport-level (that is, HTTP) errors, you must configure a Property on the TargetEndpoint that enables the
TargetEndpoint to process HTTP response codes.
By default, HTTP response codes in the 2xx-3xx range are treated as 'success'. HTTP response codes 4xx-5xx are
treated as 'failure'. Any response from the backend service with an HTTP response code 400-500 automatically
invokes the ErrorFlow. The ErrorFlow automatically returns an error message directly to the requesting client.
To create custom responses to HTTP error codes, you need to override this default behavior. In some cases you
might need to return custom errors for HTTP codes 400 and 500. For example, you may need to ensure that all
backend service URLs are obfuscated from requesting clients.
To do so, you must first configure the TargetEndpoint to treat HTTP response codes 4xx and 5xx as success
codes. By treating those codes as success codes, the TargetEndpoint takes over processing of the response
message (rather than pushing the response message into the default ErrorFlow). This enables you to define
FaultRules on HTTP error codes that invoke specific policies.
To treat HTTP error codes as success, set the success.codes property on the TargetEndpoint in your API proxy.
<TargetEndpoint name="default">
<HTTPTargetConnection>
<Properties>
<Property name="success.codes">4XX, 500</Property>
</Properties>
<URL>http://weather.yahooapis.com</URL>
</HTTPTargetConnection>
</TargetEndpoint>
You can then use HTTP response codes 400-499 and 500 to define conditional policy execution that returns a
customized response message to the requesting app.
For example, apply the following configuration to a ProxyEndpoint or TargetEndpoint response Flow.
<Response>
<Step>
<Condition>(response.status.code = 400) or (response.status.code =
500)</Condition>
<Name>ReturnError</Name>
The Flow configuration above causes the AssignMessage policy called ReturnError to generate a response
message whenever the TargetEndpoint encounters an HTTP response code of 400 or 500.
FaultRule Processing
Any number of FaultRules can be defined on ProxyEndpoints and TargetEndpoints. When an error occurs, only the
first FaultRule whose condition evaluates to true is enforced.
FaultRules are evaluated in the following order:
Request Path:
3. Fault in ProxyRequest: FaultRules defined at ProxyEndpoint execute
4. Fault in Routing: FaultRules defined at ProxyEndpoint execute
5. Fault in TargetRequest: FaultRules defined at TargetEndpoint execute
6. Fault in outbound request to target URL: FaultRules defined at TargetEndpoint execute
Response Path:
7. Fault in TargetResponse: FaultRules defined at TargetEndpoint execute
8. Fault in ProxyResponse: FaultRules defined at ProxyEndpoint execute
9. Fault in returning response to ProxyEndpoint: FaultRules defined at ProxyEndpoint execute
Policy attachments in a FaultRule are enforced in the order in which the Steps are attached to the FaultRule.
To enable fault handling for an API proxy, fault handlers must be configured to identify and categorize predefined
exception conditions, in turn enabling API Platform to execute policies that manage the exception.
Fault Taxonomy
API Platform organizes faults into the following categories and subcategories.
An error is always accompanied by a text description of the reason for the failure. When the system raises a fault,
a set of attributes are populated to assist in troubleshooting. A fault includes the following information:
This topic explains how to use these pattern matching operators in conditional statements in SAP API
Management Edge:
• Matches operator
• JavaRegex operator
• MatchesPath operator
Conditional statements are used in conditional flows, routes, and steps. You can read more about conditional
statements in the Conditions reference.
Let's look at the "Matches" or "~" conditional operator first. These two operators are the same -- the English
version, "Matches", is considered to be a more readable option.
Summary: The "Matches" operator gives you two possiblities. Either match the string literally, or do a wildcard
match with "*". As you might expect, the wildcard matches zero or more characters. Let's see how this works.
The following XML shows a Step condition. It executes the SomePolicy policy when the condition evaluates to
true. In this example, we test the variable proxy.pathsuffix, a built-in variable in SAP API Management Edge that
stores the path suffix of the request. Note, however, you can test the value of any flow variable that contains a
string. So, in this case, if the base path of the incoming request is /animals, and the request is /animals/cat, then
the path suffix is the literal string "/cat".
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>(proxy.pathsuffix Matches "/cat")</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
<Response/>
</PreFlow>
Does the policy execute? Yes, because the proxy path suffix matches "/cat" exactly. It will not execute if the suffix
is /bat or /dog or "/" or anything else.
Now, consider this conditional statement where we use the wildcard character "*":
<Condition>(proxy.pathsuffix Matches "/*at")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes, because the wildcard matches any character, and "/cat" is a match.
API Call:
GET http://artomatic-test.apigee.net/matchtest/bat
Does the policy execute? Yes, because the wildcard matches any character, "/bat" is a match.
API Call:
GET http://artomatic-test.apigee.net/matchtest/owl
Does the policy execute? Certainly not -- although the wildcard matches the "o", the letters "wl" are not matched.
Now, lets move the wildcard to the end of the suffix:
<Condition>(proxy.pathsuffix Matches "/cat*")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes, because the wildcard matches zero or more of any characters.
API Call:
GET http://artomatic-test.apigee.net/matchtest/bat
Does the policy execute? No, "/bat" is not a match.
API call:
GET http://artomatic-test.apigee.net/matchtest/cat123
Does the policy execute? Yes, the wildcard matches zero or more of any characters, therefore "123" produces a
match.
API call:
GET http://artomatic-test.apigee.net/matchtest/cat/bird/mouse
Does the policy execute? Yes, because the wildcard matches zero or more of any characters, so "/bird/mouse"
produces a match. Note how an expression like this can get you into trouble because it matches everything after
the literal characters!
Does the policy execute? No, the wildcard matches any letter (regardless of case), but the lowercase "a" does not
match "A".
API call:
GET http://artomatic-test.apigee.net/matchtest/bAt
Does the policy execute? Yes, the case matches.
Use the percent "%" character to escape reserved characters. For example:
<Condition>(proxy.pathsuffix Matches "/c%*at")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? No, the Matches operator is looking for the literal string "c*at".
API call:
GET http://artomatic-test.apigee.net/matchtest/c*at
Does the policy execute? Yes, this path, although a bit unusual, matches.
As you can see, the "Matches" operator is great for simple situations. But you can use another operator, the
"JavaRegex" or "~~" operator. These two are the same operator, except JavaRegex is considered to be more
readable. It's called JavaRegex because it allows regular expression pattern matching, and SAP API Management
Edge follows the same rules as the classes in the java.util.regex package in the Java language. The way the
JavaRegex operator works is very different from the Matches operator, so it's important not to confuse the two!
Note:
• If you're used to doing Regex in Perl scripts, it's important to note that the JavaRegex operator in SAP API
Management Edge tests the entire subject string. For example, if the subject is "abc" and the regex is "[a-z]" ,
Summary: The "JavaRegex" operator lets you use regular expression syntax in conditional statements.
The following code shows a Step condition. It executes the SomePolicy policy if the condition evalutes to true. In
this example, we test the variable proxy.pathsuffix, a built-in variable in SAP API Management Edge that stores the
path suffix of the request. Note, however, you can test the value of any flow variable that contains a string. So, in
this case, if the base path of the incoming request is /animals, and the request is /animals/cat, then the path
suffix is the literal string "/cat".
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>(proxy.pathsuffix JavaRegex "/cat")</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
<Response/>
</PreFlow>
Question: What proxy path suffix will cause SomePolicy to execute? Just like with the Matches operator, there's
only one possibility in this case.
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes, because the proxy path suffix matches "/cat" exactly. It will not execute if the suffix
is /bat or /dog or anything else.
Now, let's create a regular expression using "*" quantifier. This quantifier matches zero or more of the preceeding
character.
<Condition>(proxy.pathsuffix JavaRegex "/c*t")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? No! The "*" quantifier matches zero or more of the preceeding character, which is a "c".
API Call:
GET http://artomatic-test.apigee.net/matchtest/ccccct
Does the policy execute? Yes, because the wildcard matches zero or more of the preceeding character.
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes. The "?" quantifier matches zero or one occurance of the preceeding character,
which is an "a".
API Call:
GET http://artomatic-test.apigee.net/matchtest/ct
Does the policy execute? Yes. The "?" quantifier matches one or none of the preceeding character. In this case,
there is no "a" character, so the condition evaluates to true.
API Call:
GET http://artomatic-test.apigee.net/matchtest/caat
Does the policy execute? No. The "?" quantifier matches one of the preceeding character, which is an "a".
Next, we use the "[abc]" or "grouping" style of regex expression. It matches the characters "a" or "b" or "c".
<Condition>(proxy.pathsuffix JavaRegex "/[cbr]at)</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes. We're using regular expressions here, and the "[cbr]" expression matches a "c", "b",
OR "r". These calls are also matches:
GET http://artomatic-test.apigee.net/matchtest/bat
GET http://artomatic-test.apigee.net/matchtest/rat
But this is not a match:
GET http://artomatic-test.apigee.net/matchtest/mat
API call:
The MatchesPath operator can also be specified like this "~/". It looks a little bit like the Matches (~) and the
JavaRegex (~~) operators. But MatchesPath is entirely different.
Just remember that this operator looks at a path as a series of parts. Therefore, if the path is: /animals/cats/wild,
you can think of the path as consisting of the parts "/animals", "/cats", and "/wild".
The MatchesPath operator lets you use two wildcard notations: a single asterisk (*) and a double asterisk (**).
The single asterisk matches one path element. The double asterisk matches one or many path elements.
Let's look at an example. In this example, we test the variable proxy.pathsuffix, a built-in variable in SAP API
Management Edge that stores the path suffix of the request. Note, however, you can test the value of any flow
variable that contains a string.
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>(proxy.pathsuffix MatchesPath "/animals/*)</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
<Response/>
</PreFlow>
API call:
GET http://artomatic-test.apigee.net/matchtest/animals/
Does the policy execute? Yes, the path does have another path element (the part after "/animals/"), but it's just
empty.
API Call:
GET http://artomatic-test.apigee.net/matchtest/animals/cats
Does the policy execute? Yes, because the path has at least one element that comes after "/animals"
API Call:
GET http://artomatic-test.apigee.net/matchtest/animals/cats/wild
Does the policy execute? Yes, because the path has more than one element that comes after "/animals"
Mixing asterisks
You can use combinations of the single (*) and double (**) asterisk to further refine your path matching.
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>(proxy.pathsuffix MatchesPath
"/animals/*/wild/**)</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
API call:
All of these API calls will produce a match:
GET http://artomatic-test.apigee.net/matchtest/animals/cats/wild/
and
GET http://artomatic-test.apigee.net/matchtest/animals/dogs/wild/austrailian
and
GET http://artomatic-test.apigee.net/matchtest/animals/birds/wild/american/finches
Examples
SAP API Management Edge developers commonly want to handle both of these path suffixes: "/cat" and "/cat/".
This is because some users or clients might call your API with the extra slash on the end of the path, and you need
to be able to handle that in your conditional statements.
If you prefer, you can achieve this without using Regex like this:
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>((proxy.pathsuffix = "/cat") OR (proxy.pathsuffix =
"/cat/")</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
<Response/>
</PreFlow>
This is a good option. It is clear and readable.
You can do the same thing with Regex, however, like this. The parentheses are used to group the regex part of the
statement, but they are not required.
<Condition>(proxy.pathsuffix JavaRegex "/cat(/?)"</Condition>
API Calls:
GET http://artomatic-test.apigee.net/matchtest/cat
or
GET http://artomatic-test.apigee.net/matchtest/cat/
In all of the examples in this topic, we show how to match one of the built-in flow variables: proxy.pathsuffix. It's
good to know that you can do pattern matching on any arbitrary string or flow variable, whether or not it's a built-
in flow variable like proxy.pathsuffix.
If for example you have a condition that tests an arbitrary string, perhaps a string returned in a backend payload,
or a string returned from an authentication server lookup, you can use matching operators to test it. If you use
JavaRegex, the regular expression will be compared against the entire subject string. If the subject is "abc" and
the regular expression is "[a-z]", there is no match, because "[a-z]" matches exactly one alpha character. The
expression "[a-z]+" works, as does "[a-z]*", and "[a-z]{3}.
Let's look at a concrete example. Suppose the authentication server returns a list of roles as a comma-delimted
string: "editor, author, guest".
To test the presence of the editor role, this construction will not work, because "editor" is only part of the entire
string.
<Condition>returned_roles ~~ "editor"</Condition>
However, this construction will work:
<Condition>returned_roles ~~ ".*\beditor\b.*")</Condition>
It works because it takes into account word breaks and any other parts of the string with the .* prefix and suffix.
In this example, you can also test for "editor" with the Matches operator:
<Condition>returned_roles ~~ "*editor*")</Condition>
However, in cases where you need more precision, JavaRegex is often a better choice.
Many policy types defined by SAP API Management rely on resources. Resources are the files that implement the
code or configuration to be executed by a policy when attached to an API proxy. In some cases, as with JavaScript
and JavaCallout, a policy simply defines an attachment point in an API proxy where some code should execute. A
JavaScript or JavaCallout policy is a pointer to a resource.
Note
In the management UI, resources scoped to an API proxy are listed in the Scripts section of the
Navigation pane.
In addition to storing resources at the proxy level, API Services also provides repositories for these resources at
the organization and the environment level. By storing resources at the organization or the environment level, you
enable reuse and sharing of code and configuration across the API proxies deployed in your organization and
across different environments.
Note
The example API calls in this topic use cURL. You can also use the SmartDocs management API reference
topic SmartDocs to make the same calls.
Resource types
Note
You can also add resources at the API proxy scope in the SAP API Management UI, in the proxy editor
Develop view.
For example, all JavaScript files available across an organization are stored under:
/organizations/{org_name}/resourcefiles/jsc
JavaScript stored in the /organizations collection is available to any API proxy running in any environment.
You can list all available resources by calling GET on the collection:
$ curl https://<host:port>/v1/organizations/{org_name}/resourcefiles/{resource_type}
The following request lists all JavaScript resources at the organization level:
$ curl https://<host:port>/v1/organizations/myorg/resourcefiles/jsc
The following request lists all JavaScript resources at the environment level, in the environment called prod:
$ curl https://<host:port>/v1/organizations/myorg/environments/prod/resourcefiles/jsc
The following request lists all JavaScript resources in an API proxy revision (the most specific level):
$ curl
https://<host:port>/v1/organizations/myorg/apis/weatherapi/revisions/6/resourcefiles/j
sc
Sample response:
<List>
<Item>JavaScriptMashUp</Item>
<Item>JavaScriptClient</Item>
</List>
Note
When updating an existing resource in a deployed API proxy, you must redeploy the API proxy after to
ensure the resource changes are picked up. Newly added resources do not require API proxy
redeployment.
Let's assume that you have a simple snippet of JavaScript that you need to make available to API proxies across
your organization. The following sample JavaScript sets the HTTP request path to the value of
the proxy.basepath variable. It's just one example of a resource that you might need to put in the repository.
request.setHeader("RequestPath", flow.getVariable("proxy.basepath"));
To create a resource, you call the POST method, submitting the body of the resource file, and identifying the
resource's name and type as query parameters.
To make the JavaScript available to API proxies running in any environment in your organization:
Sample response:
{
"name" : "pathSetter",
"type" : "jsc"
}
You can also upload resources as files from your local machine as follows. It's important to use -F for the binary
upload in cURL in order for the environment- and organization-scoped JavaScript files to be accessible by the
JavaScript policy.
$ curl -X POST -H "Content-type:multipart/form-data" -F [email protected] \
https://<host:port>/v1/organizations/myorg/resourcefiles?"name=pathSetter&type=jsc" \
-u email:password
The JavaScript resource named pathSetter is now available to be referenced by policies of type JavaScript
running in any environment in the organization.
For example, to attach the JavaScript to the Request PostFlow, create a policy called PathSetterPolicy.xml that
references the filepathSetter.js:
You can add compiled Java resources as JAR files using multiple options in cURL, such as -T, --data-binary, or -
F option (not the -d option). For example:
SAP API Management resolves resource names from the most specific to the most general scope. Resource
names are resolved "up the chain", from the API proxy level, to the environment level, to the organization level.
https://<host:port>/v1/organizations/myorg/resourcefiles/jsc/pathSetter
https://<host:port>/v1/organizations/myorg/environments/prod/resourcefiles/jsc/pathSet
ter
Now imagine that an API proxy is configured with the following Policy:
<Javascript name='PathSetterPolicy' timeLimit='200'>
<ResourceURL>jsc://pathSetter.js</ResourceURL>
</Javascript>
Hint
The policy reference cannot explicitly resolve to a repository. The first resource whose name matches the
resource name in the policy is resolved.
So, when the API proxy is deployed in the environment prod, the Policy will resolve the pathSetter.js resource:
/organizations/myorg/environment/prod/resourcefiles/jsc/pathSetter
/organizations/myorg/resourcefiles/jsc/pathSetter
You can view a resource body by calling the GET method on it:
Sample response:
request.setHeader("RequestPath", flow.getVariable("proxy.basepath"));
JMS Integration
Overview
If you use Java Message Service (JMS) with Java Naming and Directory Interface (JNDI), you can make RESTful
calls from JMS to backend services through SAP API Management.
This document describes how to configure SAP API Management to work with a JMS host and how to create an
API proxy that handles incoming JMS messages.
Regardless of the JMS provider you use—for example, whether you’re using Apache ActiveMQ or JBoss HornetQ
(or neither)—the SAP API Management supports only Java Naming and Directory Interface (JNDI) to connect to
the JMS provider. If a JMS provider doesn’t support JNDI, it can't be used with SAP API Management.
Use Case
You can send messages from JMS queues to an SAP API Management API resource. For example, you might need
an API proxy endpoint to handle incoming JMS messages from multiple JMS queues, apply logic to convert JMS
messages to HTTP, forward the request to a target endpoint, and return the response as JMS.
To use JMS with SAP API Management, you configure the JMS connection details by creating a JMS host . The
JMS host then can be referenced from JMS API proxy endpoints by using
the <JMSHost> or <JMSResponseHost> tags. All JMS API proxies share the same JMS host.
Name Description
ConnectionFactory Property used to select the registry service provider as the initial context and
specifies the class name of the initial context factory for the provider. Note that it
is not used by the provider.
You might need to remove a JMS host associated with an environment. To do this, execute the following API call:
curl –u : “http://{host}:8080/v1/organizations/environments/jmshosts/{jmshost_name}” -
X DELETE
The ProxyEndpoint and JmsProxyConnection elements define a set of JMS transport properties. These properties
can be used to set network configurations to connect to the JMS provider. The SAP API Management JMS API
proxy endpoint supports only receiving messages from a JMS queue. Other JMS operations are not supported.
Ensure that you define the attribute proxyType="jmsConnection" in order to create JMS proxy endpoints.
Also, ensure that you have the JMS provider-specific client library in the classpath.
The following table provides the description of all JmsProxyConnection properties that are available for JMS
implementation.
JmsProxyConnection JMS network details associated with the API proxy. You can Yes
dynamically set to subscribe/unsubscribe to a given queue by
defining an attribute state=”on/off”. By default it is “on”.
Destination Queue path to which the subscribe listens to the messages. Yes
DefaultResponseQueue Name of the JMS queue where response from target is published. No
JMSResponseHost JMS response host defined for the JMS proxy. If specified, all No
responses are sent to the queues over this host.
Note
All HTTP headers matching standard JMS headers will be set “as is” and other HTTP headers will be set
as JMS properties in the response message used by the JMS proxy.
You can use the AssignMessage policy to specify the following headers in a JMS proxy.
X-SAP-Ignore-JMSResponse - By default, the API proxy puts the response on the JMS response queue specified
in the JMSReplyTo header. However, if you want the backend service to handle putting the response on the queue
specified in JMSReplyTo—or something else outside of the API proxy such as a Java callout or another API
proxy—add the X-SAP-Ignore-JMSResponse header and set it to true:
<Header name="X-SAP-Ignore-JMSResponse">true</Header>
CORS (Cross-origin resource sharing) is a standard mechanism that allows JavaScript XMLHttpRequest (XHR)
calls executed in a web page to interact with resources from non-origin domains. CORS is a commonly
implemented solution to the "same-origin policy" that is enforced by all browsers. For example, if you make an
XHR call to the Twitter API from JavaScript code executing in your browser, the call will fail. This is because the
domain serving the page to your browser is not the same as the domain serving the Twitter API. CORS provides a
solution to this problem by allowing servers to "opt-in" if they wish to provide cross-origin resource sharing.
Recommendation
Most modern browsers support CORS.For an in-depth description of CORS; see the Cross-Origin
Resource Sharing W3C Recommendation.
The following JQuery code calls the Yahoo Weather API. If executed from within the context of a browser (a web
page), the call will fail because of the same-origin policy:
<script>
var url = "http://weather.yahooapis.com/forecastrss?w=12797282";
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type:"GET",
url:url,
async:true,
dataType: "xml",
success: function(xml) {
// Parse the response.
// Do other things.
},
Recommendation
In the simplest case, you can return CORS headers to the client and the cross-origin request will work.
More complicated cases exist where a "preflight" request is required. You can read about preflight CORS
requests in Cross-Origin Resource Sharing W3C Recommendation, as well as in numerous articles and
blogs. See also "Handling CORS preflight requests" below
You can add CORS support to an API proxy by attaching an "Add CORS" policy to the API proxy when you create
it. To add this policy, select the Browser Access checkbox in the Add API Proxy dialog, as shown in the following
figure.
When you select this checkbox, a policy called Add CORS is automatically added to the system and attached to
the TargetEndpoint response preflow, as shown in the following figure:
The Add CORS policy is implemented as an AssignMessage policy, which adds the appropropriate headers to the
response. Here is the XML for the Add CORS policy:
<AssignMessage async="false" continueOnError="false" enabled="true" name="Add-
CORS">
<DisplayName>Add CORS</DisplayName>
<FaultRules/>
<Properties/>
<Add>
<Headers>
<Header name="Access-Control-Allow-Origin">*</Header>
<Header name="Access-Control-Allow-Headers">origin, x-requested-with,
accept</Header>
You need to manually create a new Assign Message policy and copy the code for the Add CORS policy listed in the
previous section into it. Then, attach the policy to the response preflow of the TargetEndpoint of the API proxy.
You can modify the header values as needed. For more information on creating and attaching policies, see Policy
Attachment and Enforcement.
CORS preflight refers to sending a request to a server to verify if it supports CORS. Typical preflight responses
include which origins the server will accept CORS requests from, a list of HTTP methods that are supported for
CORS requests, headers that can be used as part of the resource request, the maximum time preflight response
will be cached, and others. If the service does not indicate CORS support or does not wish to accept cross-origin
requests from the client's origin, the cross-origin policy of the browser will be enforced and any cross-domain
requests made from the client to interact with resources hosted on that server will fail.
Typically, CORS preflight requests are made with the HTTP OPTIONS method. When a server that supports CORS
receives an OPTIONS request, it returns a set of CORS headers to the client to indicate its level CORS support. As
a result of this handshake, the client knows what it is allowed to request from the non-origin domain.
For more information on preflight, refer to the Cross-Origin Resource Sharing W3C Recommendation. There are
in addition numerous blogs and articles on CORS that you can refer to.
SAP API Management does not include a CORS preflight solution out of the box, but it is possible to implement, as
described in this section. The objective is for the proxy to evaluate an OPTIONS request in a conditional flow. The
proxy can then send an appropriate response back to the client.
Let's look at a sample flow, and then discuss the parts that handle the preflight request:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ProxyEndpoint name="default">
<Description/>
<Flows>
<Flow name="OptionsPreFlight">
<PreFlow name="PreFlow">
<Request/>
<Response/>
</PreFlow>
<HTTPProxyConnection>
<BasePath>/v1/cnc</BasePath>
<VirtualHost>default</VirtualHost>
<VirtualHost>secure</VirtualHost>
</HTTPProxyConnection>
<RouteRule name="NoRoute">
<Condition>request.verb == "OPTIONS"</Condition>
</RouteRule>
<RouteRule name="default">
<TargetEndpoint>default</TargetEndpoint>
</RouteRule>
<PostFlow name="PostFlow">
<Request/>
<Response/>
</PostFlow>
</ProxyEndpoint>
The key parts of this ProxyEndpoint are as follows:
• A RouteRule is created to a NULL target with a condition for the OPTIONS request. Note that there is no
TargetEndpoint specified. If the OPTIONS request is received, the proxy immediately returns the CORS
headers in a response to the client (bypassing the actual default "backend" target). For details on flow
conditions and RouteRule, see Flow variables and conditions.
<RouteRule name="NoRoute">
<Condition>request.verb == "OPTIONS"</Condition>
</RouteRule>
• An OptionsPreFlight flow is created that adds an Add CORS policy, containing the CORS headers, to the flow if
an OPTIONS request is received.
Recommendation
RouteRules are evaluated in the order specified in the ProxyEnpoint configuration. You should always
have the default (no condition) Route at the end. Otherwise, if at the top, it will always match and never
evaluate the other Route possibilities.
This topic explains how to create API proxies for SOAP-based web services. You can create two kinds of SOAP
proxies in SAP API Management Edge. One generates a RESTful interface to the backend SOAP service and the
other performs a "pass through" of the SOAP message to the backend. Both techniques are described in this
topic.
This section explains how to create a RESTful SOAP API proxy with the REST to SOAP to REST option in the
Create New Proxy dialog.
Overview
The REST to SOAP to REST option processes the WSDL to generate a RESTful API proxy. SAP API Management
Edge determines from the WSDL the service's supported operations, input parameters, and so on. SAP API
Management Edge "guesses" which HTTP method to use for each operation. Typically, SAP API Management
Edge translates operations into GET requests, which have the advantage of being cacheable. SAP API
Management Edge also sets up the backend target endpoint, which can vary per SOAP operation.
Proxy Base Path The Proxy Base Path is a URI fragment that uniquely identifies the API that is
exposed by this API proxy. API Services uses the Base Path URI to match and route
incoming request messages to the proper API proxy. (The Base Path is appended to
the domain of the API, which is automatically generated based on
your organization name and the environment where the API proxy is deployed.) It's a
best practice to include a version number in the project name, for
example, /v1/weather. This will determine how your API is invoked by consumer
apps.
Note: The Proxy Base Path defaults to the value specified for Proxy Name converted
to all lower case unless you explicitly edit the content in the Proxy Base Path field.
5. Click Next.
6. In the WSDL page, select the API proxy type REST to SOAP to REST.
Note
A table appears listing the operations that SAP API Management "discovered" in the WSDL file. You can
select and configure which operations you wish to incorporate into your API proxy.
Recommendation
Operations on the callback porttype cannot be converted to REST resources because API Platform does
not support asynchronous operations for this purpose.
7. Select from the Port Type column which set of operations you wish to use. In WSDL, port type elements
define the operations that you can call on a web service.
Note
SAP API Management makes a "best guess" in determining the HTTP method to use for each operation. GET
is generally preferred because GET requests can be cached.
9. Optionally change the REST API path for an operation. The path will be used as the resource name in the API
proxy URL.
Note
Any parameters for an operation are listed in the REST API Parameters column. For example, the weather
API shown in the previous figure includes a ZIP parameter for certain operations. In the API proxy, you
specify that value as a query parameter.
10. Click through the rest of the wizard to add security, select virtual hosts, and deployment environment.
11. In the Build page, click Build and Deploy. SAP API Management Edge generates and deploys the new API
proxy based on the WSDL.
12. Go to the summary page for the new API proxy. Note that a set of resources have been constructed based on
the operations discovered in the WSDL file.
Recommendation
On the proxy's Overview page, the Resources list provides a detailed description of the new API, its
operations, and parameters. You can think of this representation as the API's reference documentation.
SAP API Management generates this view of the API model automatically for you. Simply expand a
resource to see its description and information about its input parameters, data types. Also listed are any
enumeration facets that apply to an input parameter. Enumeration facets specify the list of the
acceptable values for an input parameter.
When SAP API Management generates an API proxy based on a WSDL, the resulting proxy is actually a complex
flow that includes policies for transforming data extracting and setting variables, manipulating messages, adding
threat protection, and more. After you generate a proxy based on a WSDL, take a look at the resulting flow in the
Develop view of the API management UI. There, you can see exactly which policies have been added.
For example, the following figure shows the Target Endpoint Preflow part of a SOAP-based proxy. On the
request side, an AssignMessage policy is used to set the target URL. On the response side, policies execute to
transform the response from XML to JSON, extract the SOAP body part of the response into a variable, and set
the response message. These policies (and others) are added automatically when you create the proxy.
OpenAPI Spec: To view the auto-generated OpenAPI Spec for this proxy,
visit http(s)://[proxy_domain]/[proxy_base_path]/openapi.json. However, the conversion is not
always accurate, since not all the rules of an XML schema can be represented in an OpenAPI Spec.
This section explains how to create a pass-through proxy with the Pass-Through Proxy option in the Create New
Proxy dialog.
Overview
The Pass-Through Proxy option lets you to create a proxy that passes the SOAP message in a request to the
backend service "untouched", making it very easy to create a proxy for a SOAP-based web service. Behind the
scenes, SAP API Management handles any transformations and other flow activities for you automatically. For
example, if the request happens to be in JSON format, SAP API Management takes steps to convert it to a valid
XML SOAP message with correct namespaces before POSTing it to the service. Similarly, when the service
returns an XML-based SOAP response, SAP API Management translates it back to JSON before returning it to the
client. In addition, SAP API Management sets up the backend target endpoint, which can vary per SOAP
operation.
Note:
You might wish to choose Pass-Through if the WSDL operations support a lot of unbounded parameters. It's
easier for SAP API Management to translate a WSDL containing bounded parameters to a proxy, because they are
finite and therefore can be represented by a finite set of query parameters or form variables.
For this type of proxy, SAP API Management Edge hosts the WSDL and creates a flow in the proxy to let you
access it. The address to this SAP API Management Edge-hosted
WSDL, http(s)://[proxy_domain]/[proxy_base_path]?wsdl, becomes the new service endpoint URL for
clients calling the SOAP service through the proxy.
Basic Steps
Proxy Base Path The Proxy Base Path is a URI fragment that uniquely identifies the API that is
exposed by this API proxy. API Services uses the Base Path URI to match and route
incoming request messages to the proper API proxy. (The Base Path is appended to
the domain of the API, which is automatically generated based on
your organization name and the environment where the API proxy is deployed.) It's a
best practice to include a version number in the project name, for
example, /v1/weather. This will determine how your API is invoked by consumer
apps.
5. Click Next.
6. In the WSDL page, select the API proxy type Pass-Through SOAP.
Note
A table appears listing each WSDL operation and its corresponding SOAP payload. This is the payload
that is "passed through" to the backend SOAP service.
7. Select from the Port Type column which set of operations you wish to use. In WSDL, port type elements
define the operations that you can call on a web service.
8. Click through the rest of the wizard to add security, select virtual hosts, and deployment environment.
9. In the Build page, click Build and Deploy. SAP API Management Edge generates and deploys the new API
proxy based on the WSDL.
In the proxy's Overview page, the Resources list provides a detailed description of the new "pass-through" API
proxy. You can think of this representation as the API's reference documentation. SAP API Management
generates this view of the API model automatically for you. Simply expand a resource to see its description. The
SOAP message body that is POSTed to the backend service is captured in the model view, as shown in this figure.
Note that the method used for Pass-Through proxies is POST. This is the only method supported by the SOAP
protocol.
When SAP API Management generates a pass-through proxy, the resulting proxy is actually a complex flow that
includes policies for transforming data, extracting and setting variables, manipulating messages, adding threat
protection, and more. After you generate the pass-through proxy, take a look at the resulting flow in the Develop
view of the API management UI. There, you can see exactly which policies have been added.
For example, the following figure shows the Target Endpoint Preflow part of a pass-through proxy. On the request
side, an AssignMessage policy is used to set the target URL. On the response side, policies execute to transform
the response from XML to JSON, extract the SOAP body part of the response into a variable, and set the response
message. These policies (and others) are added automatically when you create the proxy.
Note
When you face any issue with the request and response, refer the "SAP NOTE 0002115216".
SAP API Management Edge-hosted WSDL: To see the SAP API Management Edge-hosted WSDL generated for
this type of proxy, go to http(s)://[proxy_domain]/[proxy_base_path]?wsdl.
The previous sections covered the creation of a SOAP-to-REST API proxy using the API proxy wizard in SAP API
Management Edge. However, if you want more fine-grained control over the SOAP-to-REST transformation, you
can bypass the automation provided by the wizard and build a proxy by manually adding and configuring policies
to get the behavior you want.
After reading this topic you will know how to enable streaming HTTP requests and responses to and from API
proxies deployed to SAP API Management.
By default, HTTP streaming is disabled and HTTP request and response payloads are written to a buffer in
memory before they are processed by the API proxy pipeline. You can change this behavior by enabling
streaming. With streaming enabled, request and response payloads are streamed without modification to the
client app (for responses) and the target endpoint (for requests).
If your API proxy handles very large requests and/or responses, you may wish to enable streaming. For example,
you may wish to enable a streaming response flow if you have a Node.js application deployed on SAP API
Management that returns output over time, such as a Comet-style application. Or, you may wish to enable
streaming for any application that accepts or returns a very large amount of data.
Note
If your API requests or returns a large amount of data, you may see this HTTP error:
{"fault":"{\"detail\":{\"errorcode\":\"protocol.http.TooBigBody\"},\"faultstring
\":\"Body buffer overflow\"}"}
If you see this error, we recommend that you enable streaming. If you continue to see the error after you
enable streaming, consider removing any policies that require access to the request or response payload.
When streaming is enabled, policies that require access to the request or response payload, such as XSLT
transformations and XML to JSON policies cannot be run and are bypassed.
To enable request streaming you need to add the request.streaming.enabled property to the ProxyEndpoint
and TargetEndpoint definitions in the proxy bundle and set it to true. Similarly, set
the response.streaming.enabled property to enable response streaming.
This topic provides a quick overview of proxy deployment. You can deploy proxies using the Management UI,
command-line scripts, or with APIs.
When you create an API proxy you'll need to decide which environment you'll be working in. You can choose to
create a new API proxy on production, but that is not recommended as you may expose an API to developers
before its ready. In general you want to start by creating an API proxy in test which, after testing, you then
'promote' to prod.
As you work on an API proxy, API Platform saves iterations of your configuration as revisions. When you deploy an
API proxy, you choose a specific revision to deploy. Typically, you deploy the most recent revision, and, if
necessary, revert to the previous revision number. You can choose where to deploy those revisions. For instance,
you can promote a revision to prod to allow developers to start working with your API. At the same time, you may
be iterating multiple revisions on test, where you're adding features or fine-tuning policies. Then, when you're
ready, you can deploy the new revision to prod, overwriting the existing revision on that environment. Using this
method, you can always have a live revision of your API available to developers while you're developing
Promotion to Prod
When an API proxy has been fully implemented and tested, it is ready to be promoted to 'prod'. The revision of the
API proxy in test will be used to overwrite the revision of the API proxy deployed on prod.
API Platform provides capabilities to ensure seamless deployment of API proxies, minimizing the impact on apps
and end users during the deployment procedure.
Scripting Deployment
The SAP API Management management UI enables you to deploy API proxies to prod directly from the API proxy
builder. However, in many situations the requirements for security, reliability, and consistency will mandate that
development teams script deployment procedures. To do so, you can write code and scripts that invoke the
RESTful API exposed by API Platform.
Environment Resources
For additional control during promotion, it is recommended that you only iterate on API proxies in test, and make
as few changes as necessary to API proxies deployed in prod.
To do so, you need to ensure that certain resources associated with each environment are configured in such a
way that they can remain static in an API proxy configuration.
Target URLs: It is common for API proxies to call different backend URLs during testing and production. You can
use TargetServer configurations to create environment-independent TargetEndpoint configurations. See Load
Balancing Across Backend Servers.
Understanding Deployment
A proxy must be deployed before it can be invoked. Generally, it's up to you when you deploy. When you are
working in a test environment, you may deploy iteratively many times. On the other hand, the decision to deploy a
proxy from the test environment to a production environment usually depends on lifecycle rules established by
your development team.
Deploy or redeploy a proxy when you:
• Create a new proxy (deployment happens automatically)
• Modify an existing proxy
• Create a new revision of a proxy
• Create a new version of a proxy
• Push a proxy from one environment to another, such as from a test environment to a production
environment.
• Delete and recreate a keystore.
You deploy a proxy to an environment. All organizations in SAP API Management, by default, have two
environments called test and prod. These environments are merely designed to provide you with one area to work
on and test API changes, and another area where APIs are exposed to apps. The following figure shows a proxy
that is deployed to the test environment, as indicated by the green dot.
How you deploy a proxy depends on where you are developing the proxy. If you are working in the UI, you can
easily deploy a proxy with just a couple of mouse clicks. A new proxy is automatically deployed when you create it;
you don't have to do anything special. The procedure for redeploying an existing proxy is almost as simple. Just
select which deployment environment to deploy to, and the management UI takes care of the rest. For more
information, see Deploying proxies in the UI.
If you are developing proxies and related components offline (that is, working with proxy XML files and other code
directly on your file system), SAP API Management provides a convenient command-line deployment tool that
you can use. You can also obtain a sample shell script that you can configure and run to upload and deploy your
proxy files. For more information, see Deploying proxies from the command line.
Finally, you can use the SAP API Management API to deploy proxies. The deployment APIs exposes atomic
functions that your development team can coordinate to automate and optimize your API development lifecycle.
See Deploy API proxies using the management API.
Revisions let you manage API proxy updates as you create and deploy them to an environment. Revisions are
sequentially numbered, enabling you to revert changes by deploying a previous revision of your API proxy. Only
one revision of an API proxy can be deployed in an environment at a given time.
Typically, an existing revision must be undeployed before a new one can be deployed. Other advanced options
include overwriting a deployed revision or opting not to increment a revision at all. For example, sometimes when
you make minor changes, you might not want to increment the revision. These advanced options can be
accomplished through direct calls to the SAP API Management API. See Deploy API proxies using the
management API.
You can deploy a revision of an API proxy into the prod environment, while continuing to create new revisions of
that API proxy in the test environment. When you are ready, you can "promote" the higher revision of your API
proxy from the test environment over the prior revision of the API proxy in the prod environment.
For more information on revisions, see Deploy API proxies using the management API. See also Deploying proxies
in the UI.
While a revision usually represents a relatively minor update, made in the course of a development cycle, the
version of an API proxy should change relatively infrequently. Typically, a version reflects a significant change in
Note
Don't confuse the version of an API (that is, the public interface) with the revision of an API proxy (that is,
the internal number associated with a configuration). The two numbers are unrelated, and the revision
number of an API proxy is totally opaque to apps that consume your API.
As an API provider, you need to determine when it's appropriate to release a new version. For more information,
see the next section, "Versioning best practices."
Keep the following best practices in mind when you consider versioning:
• Never release an API without a version.
• Make the version mandatory.
• Specify the version with a "v" prefix. Place the prefix to the far left in the URL so that it has the highest scope,
e.g., /v1/dogs.
• Use a single ordinal number, such as v1, v2, and so on.
• Make the version part of the API base path
• Maintain at least one version back.
• Set up a reasonable deprecation policy. Give developers plenty of time and warning before deprecating
features. Depending on your developer's platform, that can be six months or two years. For example, mobile
apps take longer to rev than web apps.
Note
Do not use the dot notation, like v1.2 for an API proxy version. This implies a granularity of versioning that
doesn't work well with APIs.
All organizations in SAP API Management, by default, have two environments: test and prod. The naming is
arbitrary. These environments are merely designed to provide you with one area to work on and test API changes,
and another area where APIs are exposed to apps.
Note
Depending on your role, you may not be able to deploy to all environments. Users can only deploy to
the test environment. If you're an administrator you can deploy to any environment.
You can deploy multiple revisions of an API. It's common to have a revision in prod while another revision is
in test as it's being tested or developed. As long as the API proxy base path stays the same, each environment can
only have one deployed revision of an API. For example, you could have revision 1 deployed in test and revision 20
deployed in prod. You can view deployment of all revisions on the Overview page of the API proxy editor.
When you create a new revision of an API proxy without changing its base path, then deploy it to an environment
in which it's already deployed, the previous version is undeployed and the new revision is deployed in its place.
Note that deployment through the management UI might impact inbound calls. To handle and transition inbound
calls more gracefully during deployment, use the management API.
1. In the API proxy editor, select the revision you want to deploy.
2. Choose Deployment > {environment} and respond to the confirmation dialog.
If the API proxy base path is the same as another deployed revision in that environment, the former revision is
undeployed and the new revision is deployed in its place.
For deploying multiple revisions in the same environment, see the next section.
Note
You can also undeploy a revision by performing the previous steps on an already deployed revision,
indicated by a green dot next to the environment name.
You can deploy multiple revisions of an API proxy in a single environment by changing the proxy's base path,
saving the proxy as a new revision, and deploying the new revision.
For example, this is a great way to create multiple versions of an API proxy by specifying /v1, /v2, /v3, etc. in the
base path. You could deploy all of those revisions to a single environment (such as test). Each proxy could be
completely different, with different flows, policies, and configurations, and you could make API calls to each in the
test environment.
To create and deploy a new API proxy revision by changing the base path
1. Go to the Develop page. In the Navigator, select one of the Proxy Endpoint flows (such as the default item or
PreFlow).
2. Change the value of the <BasePath> element.
3. Select Project > Save as New Revision.
At this point, you can make any flow, policy, or other configuration changes you want to the API proxy and
choose Save.
4. Deploy the new revision by selecting Deployment > {environment}.
On the Overview page, you can see your multiple revisions, all with different base paths, deployed to the same
environment.
The SAP API Management Python deploy tool works with the SAP API Management API to import and deploy API
proxies. The tool is available as part of the API Platform Samples distribution on GitHub.
Use the SAP API Management Python tool to import (upload) and deploy your API in one simple process.
The deploy tool must be run from the base directory in the distribution of the API Platform Samples distribution,
where the base directory is the parent directory of the setup and tools directory.
For example:
$ python tools/deploy.py -n weatherapi -u [email protected]:foo -o myCo -e test -d
weatherapi -p /
This command zips your files, pushes them to your organization on SAP API Management, and deploys them to
the specified environment.
The deploy tool automatically discovers the current revision of your API proxy, undeploys the existing revision,
and deploys an incremented revision of the API proxy.
You can use this tool to upload the API proxy to an on-premises version of SAP API Management by specifying
the -h flag:
$ python tools/deploy.py -n weatherapi -u [email protected]:foo -o myCo -e test -d
weatherapi -p / -h https://192.168.11.111:8080
In this example, you specify the IP address of the SAP API Management server. If you have created a DNS record
for the management server, you can specify a URL in the form https://ms_URL:8080.
The complete list of flags for the command are:
• -n: The name of your API proxy.
• -u: The username and password for your account in an organization in SAP API Management.
• -o: The name of the organization in which you have an account.
• -e: The environment to which the API proxy should be deployed (test or prod).
• -d: The path to the directory containing your API proxy files. Your API proxy files must be stored under a
directory named "apiproxy". This value is the path of the directory that contains the "apiproxy" directory, and
not to the path to the "apiproxy" directory itself.
• -p: The URI path used as a pattern match to route incoming message to this API proxy deployment. In most
cases, you can set this value to '/', unless you have advanced deployment and routing requirements. The
primary path used for API proxy routing is defined in the API proxy's ProxyEndpoint configuration file.
The shell script described in this section is included with the API Platform Samples distribution. This section
assumes that you have obtained the shell script.
The easiest approach is to run the deploy script provided with the sample API proxy. The shell scripts wrap the
SAP API Management Python deploy tool.
From the /simplyProxy directory run:
$ sh deploy.sh
You should see:
Enter your password for user {myname} in the SAP API Management Enterprise
organization {org_name}, followed by [ENTER]:
Enter your password for user Your USERNAME on enterprise.sap.com in the SAP API
Management organization Your ORG followed by [ENTER]:
it means that you need to modify the /setup/setenv.sh file in the platform samples distribution.
On success, the deploy tool ZIPs up the files under /apiproxy, imports the package to your organization on SAP
API Management, and then deploys the API proxy to the 'test' environment.
Your API proxy is ready to be invoked.
Every organization has a unique software development lifecycle (SDLC). It is often necessary to synchronize and
align API proxy deployment with the processes used for backend services.
The API methods demonstrated in this topic can be used to integrate API proxy management into your
organization's SDLC. A common usage of this API is to write scripts or code that deploy API proxies, or that
The following steps walk you through simple interactions with the APIs.
Get an API
You can call the GET method on any API proxy in your organization. This call returns a list of all available
revisions of the API proxy.
$ curl -u myname:mypass -H "Accept: application/json"
http://<host:port>/v1/o/{org_name}/apis/weatherapi
Sample Response:
{
"name" : "weatherapi",
"revision" : [ "1" ]
}
The only detail returned by this method is the name of the API proxy along with the associated 'revision', which
has an associated number. API proxies consist of a bundle of configuration files. Revisions provide a lightweight
mechanism for managing your updates of the configuration as you iterate. Revisions are sequentially numbered,
enabling you to revert changes by deploying a previous revision of your API proxy. Also, you can deploy a revision
of an API proxy into the prod environment, while continuing to create new revisions of that API proxy in the test
environment. When you are ready, you can 'promote' the higher revision of your API proxy from the test
environment over the prior revision of the API proxy in the prod environment.
In this example, there is only one revision because the API proxy was just created. As an API proxy moves through
the lifecycle of iterative configuration and deployment, the revision number increments by integers. Using direct
API calls to deploy, you can optionally increment the revision number of the API proxy. Sometimes when you
make minor changes, you might not want to increment the revision.
Note
Don't confuse the version of an API (that is, the public interface) with the revision of an API proxy (that is,
the internal number associated with a configuration). The two numbers are unrelated, and the revision
number of an API proxy is totally opaque to apps that consume your API.
The API version (for example, api.company.com/v1) should change very infrequently. When you do increment the
API version, it signifies to developers that there has been a significant change in the signature of the external
interface exposed by the API.
The API proxy revision is merely an incremented number associated with an API proxy configuration. API Platform
maintains revisions of your configurations so that you can revert a configuration when something goes wrong. By
default, an API proxy's revision is automatically incremented every time you deploy an API proxy. This behavior
can be overridden in the management UI and in the API.
To obtain the detailed profile of an API proxy configuration, you call the GET method on a specific revision
number.
For example, you can call the GET method on API proxy revision 1 to get a detailed view.
$ curl -u myname:mypass -H "Accept:application/json"
http://<host:port>/v1/o/{org_name}/apis/weatherapi/revisions/1
Sample Response
{
"configurationVersion" : {
"majorVersion" : 4,
"minorVersion" : 0
},
"contextInfo" : "Revision 1 of application weatherapi, in organization
{org_name}",
"createdAt" : 1343178905169,
"createdBy" : "[email protected]",
"lastModifiedAt" : 1343178905169,
"lastModifiedBy" : "[email protected]",
"name" : "weatherapi",
"policies" : [ ],
"proxyEndpoints" : [ ],
"resources" : [ ],
"revision" : "1",
"targetEndpoints" : [ ],
"targetServers" : [ ],
"type" : "Application"
}
These API proxy configuration elements are documented in detail in the API proxy configuration reference.
Recommendation
As you've seen, you deploy the API revision to an environment, so the first step in deploying API proxy
revisions is to verify the list of environments in your organization.
Sample Response:
[ "test", "prod" ]
Explore Deployments
A "deployment" is a revision of an API proxy that has been deployed in an environment. An API proxy that is in the
'deployed' state is accessible over the network, at the addresses defined in the VirtualHost for that environment.
Recommendation
It is often useful to check to see in which environment (and if!) your API is deployed. For example, you
might find requests to your API proxy are failing. One troubleshooting step is to ensure that the API proxy
is deployed as expected.
API proxies cannot be invoked until they have been deployed. API Platform exposes RESTful APIs that provide
control over the deployment process.
The following APIs are called on your behalf by the Python deploy tool. The deploy tool provides support for
packaging and importing API proxies that you develop locally, and it also manages undeployment of existing API
Note
Using this approach, there will inevitably be some lag between the time when the first package is
undeployed and the next one is deployed. During this interval, calls from apps may be rejected with an
HTTP code 5xx. If this is a problem, as it usually is in production deployments, use the seamless
deployment option, described below.
Seamless Deployment
To minimize the potential for downtime during deployment, use the override option on the deployment method,
and set it to true.
You cannot deploy one revision of an API proxy on top of another. The first must always be undeployed. By
settingoverride to true, you indicate that one revision of an API proxy should be deployed over the currently
deployed revision. The result is that the deployment sequence is reversed--the new revision is deployed, and once
the deployment is complete, the already deployed revision is undeployed.
$ curl -X POST -H "Content-type:application/x-www-form-urlencoded" \
http://<host:port>/v1/o/{org_name}/environments/{env-
name}/apis/{api_name}/revisions/{revision_number}/deployments?"override=true" \
-u myname:mypass
You can further optimize deployment by setting the delay parameter. The delay parameter specifies a time
interval, in seconds, before which the previous revision should be undeployed. The effect is that in-flight
transactions have a time interval in which to complete before the API proxy processing their transaction is
undeployed. Following is what occurs with override=true and the delay parameter set:
• Revision 1 is handling requets.
• Revision 2 is being deployed in parallel.
• When Revision 2 is fully deployed, new traffic is sent to Revision 2. No new traffic is sent to Revision 1.
• However, Revision 1 may still be processing existing transactions. By setting the delay parameter (for
example, 15 seconds), you give Revision 1 15 seconds to finish processing existing transactions.
• After the delay interval, Revision 1 is undeployed.
$ curl -X POST -H "Content-type:application/x-www-form-urlencoded" \
When override=true is used along with a delay, HTTP 5xx responses during deployment can be eliminated. This is
because both API proxy revisions will be deployed simultaneously, with the older revision undeployed after the
delay.
This returns the same result as above for all API proxies deployed in all environments.
Since the API is RESTful, you can simply use the POST method, along with a JSON or XML payload, against the
same resource to create an API proxy.
A profile for your API proxy is generated. The default representation of an API proxy is in JavaScript object
notation (JSON). Below is the default JSON response to the POST request above, which created an API proxy
called 'weatherapi'. A description of each element in the profile follows:
{
"configurationVersion" : {
"majorVersion" : 4,
Note
Keep in mind that the response payload merely contains a representation of an API resource — you can
create an API proxy using JSON or XML, and you can also retrieve representations of the API proxy as
XML or JSON, depending on your needs.
The API proxy profile that is generated demonstrates the complete structure of an API proxy:
• APIProxy revision: The sequentially numbered iteration of the API proxy configuration, as maintained by
API Platform
• APIProxy name: The unique name of the API proxy
• ConfigurationVersion: API Platform version to which the API proxy configuration conforms
• CreatedAt: Time when the API proxy was generated, formatted in UNIX time
• CreatedBy: Email address of the user who created the API proxy
• DisplayName: A user-friendly name for the API proxy
• LastModifiedAt: Time when the API proxy was updated, formatted in UNIX time
• LastModifiedBy: Email address of the user who updated the API proxy
• Policies: A list of policies that have been added to this API proxy
• ProxyEndpoints: A list of named ProxyEndpoints
• Resources: A list of resources (JavaScript, Python, XSLT) available to be executed in this API proxy
• TargetServers: A list of named TargetServers (that can be created using the management API), used in
advanced configurations for load balancing purposes
• TargetEndpoints: A list of named TargetEndpoints
Note that many of the elements of the API proxy configuration created using the simple POST method above are
empty. In the following topics, you will learn how to add and configure the key components of an API proxy.
Security Guidelines
The SAP Management API relies on HTTP Basic Authentication. You need to provide a username and password
for each API call.
In some situations, it is not practical to collect the password when the script runs. For example, you may need to
run a cron job that fires when no administrators are present. In these situations, you need to make the password
available to the script without any human intervention.
Follow these guidelines:
1. Centralize credentials in a single file that is used as a source for the programs and scripts that you write
2. Protect the credentials source file to the extent possible using file system security and permissions
3. Create an automation client with highly restricted permissions on specific resources in your organization.
Node.js adds more programmability to the API platform. Running on SAP API Management, Node.js apps take
advantage of SAP API Management's enterprise-grade operations like traffic management, security, deployment
tools, revision control, logging, and analytics. Furthermore, you can leverage thousands of third-party Node.js
modules in your APIs.
This topic explains the simplest way to wrap a Node.js application in an API proxy using the management UI.
Chances are, the first Node.js app you ever created was an HTTP server that responds to requests with "Hello
World!" The simplest way to try out Node.js is to do something very similar. With just a few mouse clicks, you'll
have a functioning, proxied Node.js HTTP server running on SAP API Management. After that, you can use the
code editor in the UI to modify the Node.js app, add additional Node.js files, add policies, and so on.
This section explains how to create an API proxy that interacts with a Node.js HTTP server. The Node.js HTTP
server code is already written for you and is automatically deployed to SAP API Management when you follow
these simple steps.
1. Log in to the SAP API Management UI.
2. From the APIs menu, select API Proxies.
3. In the API Proxies summary page, click +API Proxy.
4. In the New API proxy dialog, select New Node.js.
Note
Use the Node.js Sample "Integrated API BaaS" option only when SAP API Management's API BaaS
component is installed.
5. From the Node.js Server Type options, select Node.js Sample "Hello World".
6. Provide a Name for the proxy. You can just enter Hello.
7. Provide a Project Base Path. If you specified Hello as the display name, then the path /hello is populated
automatically.
8. Add a version number /v1 to the path. API versioning is a best practice. The new Project Base Path is:
/v1/hello
9. Optionally, provide a Description.
When you call the hello proxy, the Node.js application executes automatically, responding with "Hello, World!".
Note that unless you specified otherwise, the Node.js application is deployed to the environment called test.
Here's the basic call using Curl (substitute your hostname and port).
$ curl http://{hostname}:{port}/v1/hello
Hello, World!
Let's look at the Node.js code that was added to the API proxy. Go to the summary page for the Hello World proxy
and choose Develop.
This opens the Develop view which includes a code editor. You can edit the code there directly.
This topic explains how to deploy a Node.js application from your local system to SAP API Management. In this
topic, we'll discuss how to use a command-line tool called SAP API Managementtool to deploy Node.js
applications to SAP API Management.
You can deploy an existing Node.js API application, including any dependent Node.js modules, from your local
system to SAP API Management using a command-line utility called SAP API Managementtool. The utility
automatically bundles the application and its dependencies into an API proxy and deploys it on SAP API
Management.
For example, let's say you used Express to create a web application in Node.js. The application runs as an HTTP
server that listens for HTTP requests, processes those requests, returns data, and so on. When you use SAP API
Managementtool to deploy a Node.js application to SAP API Management, it's wrapped in a proxy and executes
within the context of the API platform. You can then call your application through its new proxy URL, and you can
add value to it by "dressing it" with standard SAP API Management features like OAuth security, quota policies,
threat protection policies, conditional flows, caching, and many others.
When you run the SAP API Managementtool utility with the deploynodeapp option, it:
Before you begin, you need to install the SAP API Management tool utility.
You can install SAP API Management tool through npm.
The SAP API Management tool module and its dependencies are designed for Node.js and is available
through npm using the following command:
$ sudo npm install -g apigeetool
Example
$ curl http://{hostname}:{port}/myNodeApp
Hello, My Node App!
If you wish, log in to you’re your SAP API Management account and go to the API Proxies page of the
management UI. You will see your new proxy listed there.
If your Node.js application depends on installed modules, SAP API Management tool handles them by zipping the
node_modules folder and adding it to the proxy bundle. No additional action is necessary. The same is true for any
directories that contain additional source code. The SAP API Management tool utility zips them and deploys them
with the bundle.
You cannot edit files in these zipped directories on the SAP API Management UI's editor. If you need to change
them, you can export your project, edit the files locally, and then redeploy using SAP API Management tool or by
importing the exported project using the management UI. See also "Exporting and importing a proxy with Node.js
code".
For basic usage information on the SAP API Management tool utility's input parameters, enter:
$ apigeetool deploynodeapp -h
Usage: deploynodeapp -n [name] -o [organization] -e [environment]
-d [directory name] -m [main script file]
-u [username] -p [password]
-b [base path] -l [Management server url] -z [zip file] -i -h
-o SAP API Management organization name
-e SAP API Management environment name
-n SAP API Management proxy name
-d SAP API Management proxy directory
-m Main script name: Should be at the top level of the directory
-u SAP API Management user name
-p SAP API Management password
-b Base path (optional, defaults to /)
-L Management Server hostname and port
-z ZIP file to save (optional for debugging)
-i import only, do not deploy
-h Print this message
Another way to integrate an existing Node.js application into an API proxy is to add the application when you
create the proxy. You can do this entirely through the management UI and the New API Proxy dialog.
Note
If you upload multiple Node.js files, you need to specify which one is the main file. (The main file is the one
that you would invoke from the command line with the node command.)
4. Give the proxy a name. In this example, we are calling it hellonode.
5. Add the version /v1 to the Project Base Path. Versioning your API is a best practice.
6. Choose Build.
7. Choose Develop to enter the Develop view.
8. Open the TargetEndpoint file in the code editor.
9. Be sure the <ScriptTarget> element specifies the main Node.js file, as follows:
<ScriptTarget>
<ResourceURL>node://server.js</ResourceURL>
<Properties/>
</ScriptTarget>
10. Choose Save.
Another way to add Node.js code to a proxy is to add it directly, either through the UI or by uploading it from your
local filesystem. You can also specify which Node.js file is the main file, which is the file invoked when the proxy is
deployed.
Note
Only one Node.js source file is designated to be the main file. The main file is the one you would execute
from the command line to run a Node.js application. The main file is specified in the proxy's target
endpoint definition file using an element called <ScriptTarget>, as explained in Invoking an imported
Node.js file and in Adding Node.js to an existing API proxy. In these out-of-the-box examples, the correct
target endpoint definition is created for you.
To create a new Node.js resource file:
1. In the Develop view, select New Script from the New menu.
2. In the Add Script dialog, select the file type Node and name the script.
3. Choose Add.
Note
Recall that the Proxy Endpoint defines how clients call your API. When a client calls the API with the new
base path, processing is routed to the Target Endpoint, where the main Node.js file is specified.
1. Under Proxy Endpoints in the Navigator, choose the name of the proxy endpoint (usually called default).
2. In the Code editor, edit the <HttpProxyConnection> element by changing the <BasePath> to whatever
name you wish. For example, if the current <BasePath> is v1/hello and you wanted it to be v1/my-node-
file, change the <BasePath> element like this:
<BasePath>/v1/my-node-file</BasePath>
3. Choose Save.
4. Invoke the proxy using the new base path, like this:
$ curl http://{hostname}:{port}/v1/my-node-file
Hello, World!
After you deploy a proxy containing Node.js code to SAP API Management, you can always export the proxy back
to your system, work on it there, and then re-import it back using the management UI. This sort of round-trip
development technique is commonly used.
1. From the API proxy summary page, choose Develop.
2. In the Develop page, select Download Current Revision.
3. Unzip the downloaded file on your system.
Note
The Download function does not unzip any directories that were zipped when the proxy was deployed, like
node_modules or other folders with source code in them. You'll need to unzip them manually once the
proxy is downloaded to your system.
You can import the proxy bundle back into SAP API Management by selecting Import Into New Revision from the
same menu.
You can view the output of this console.log message in the trace tool. Simply call your API in the trace tool and
open the Script Output panel of the final response, as shown below.
The trace tool is useful for general proxy debugging. For detailed information on using the trace tool, see Using the
Trace tool.
You can embed console.log statements in your Node.js code and view the output in the trace tool. For example,
the following statement prints the username of the user who is logging in to access the proxy:
console.log('Logging in as %s', config.username);
Assert Supported
Buffer Supported
Domain Supported
Events Supported
http Supported The virtual host and path for incoming requests is
specified in the API Proxy, not by the HTTP
module. See "Understanding support for the http
and https modules" for more information.
module Supported
path Supported
module Supported
punycode Supported
querystring Supported
module Supported
STDIO Supported Standard output and error are routed to a log file
within the SAP API Management infrastructure.
There is no standard input for scripts running on
SAP API Management. However, you can pass
arguments using the ScriptTarget element of
TargetEndpoint. See Advanced ScriptTarget
configuration for more information.
string_decoder Supported
timers Supported
url Supported
util Supported
vm Supported
zlib Supported
All Node.js applications running in SAP API Management must use the http or https module to listen for incoming
requests. If you were to deploy a script that doesn't listen for incoming requests, it would simply execute and exit.
The listen method of the http and https modules in Node.js takes a port number as a parameter. For example:
svr.listen(process.env.PORT || 9000, function() {
console.log('The server is running.');
});
This "port" argument is required in Node.js, but SAP API Management ignores this parameter. Instead, the API
proxy in which the Node.js script runs specifies the "virtual host" that it listens on, and the Node.js application
uses those same virtual hosts, just like any other SAP API Management proxy.
Every environment in SAP API Management has at least one virtual host. The virtual host defines the HTTP
settings for connection with the SAP API Management organization. All API proxies in an environment share the
same virtual hosts. By default, two virtual hosts are available for each environment: default and secure.
The SAP API Management tool deploynodeapp command generates an SAP API Management proxy wrapper
around the Node.js application. When deployed, the Node.js application listens on the default virtual host defined
for the environment.
SAP API Management supports the Node.js tls module. This module uses OpenSSL to provide Transport Layer
Security (TLS) and/or Secure Socket Layer (SSL) encrypted stream communication. You can use the tls module
to create secure connections to backend services from Node.js applications running on SAP API Management.
To understand how the tls module works on SAP API Management, it's important to understand how virtual hosts
are used on SAP API Management. Every environment in SAP API Management has at least one virtual host. The
virtual host defines the HTTP settings for connection with the SAP API Management organization. All API proxies
in an environment share the same virtual hosts. By default, two virtual hosts are available for each environment:
default and secure.
Now, let's look at how SAP API Management handles TLS (SSL) communication for incoming and outgoing
requests on Node.js applications:
SAP API Management does not support the "cluster" module, which allows Node.js applications to control when
additional copies of an application are started and stopped, and to communicate with them. In the parlance of the
"cluster" module, all Node.js applications are considered to be the "master."
However, SAP API Management does deploy multiple instances of each application — two in most cases, although
the system may be configured to run more if necessary.
That means that Node.js applications running inside SAP API Management, like all Node.js applications, must
assume that they will be processing many different requests "in parallel" using a single thread of control. However,
the application must not assume that it is the only copy running in the world, though it also must not assume that
there is some way to communicate with the other copies.
In the <TargetEndpoint> definition, the <ScriptTarget> element takes additional optional parameters
besides <ResourceURL>. You can also pass command-line arguments and environment variables to a Node.js
script using the <EnvironmentVariables> and <Arguments> parameters:
<TargetEndpoint name="default">
<ScriptTarget>
<ResourceURL>node://hello.js</ResourceURL>
<EnvironmentVariables>
<EnvironmentVariable name="NAME">VALUE</EnvironmentVariable>
</EnvironmentVariables>
<Arguments>
<Argument>ARG</Argument>
</Arguments>
</ScriptTarget>
</TargetEndpoint>
The SAP API Management-access module lets you access API proxy flow variables and caches from within
Node.js application code.
The SAP API Management-access module is integrated into the SAP API Management platform. When you deploy
Node.js code to SAP API Management, this module is available to you. You simply need to require it in any Node.js
code that you deploy. For example:
var access=require('sap-access');
You can also download SAP API Management-access for local development and testing. The SAP API
Management-access packaged module is available through npmjs.org.
When you deploy a Node.js application to SAP API Management, you can access any of the supported "out-of-the-
box" flow variables, flow variables created by policies, and any flow variables that you create yourself from within
your Node.js code. Flow variables are created and exist within the context of an API proxy running on SAP API
Management.
getVariable
Parameters:
• httpRequest: The request object that comes from the http module.
• name: (String) The name of the variable to retrieve.
Returns:
A string or a number, depending on the type that was set using setVariable(), when it was created by you
elsewhere, or when a policy created it. If you are accessing one of the out-of-the-box SAP API Management
variables, you can find a list of types in the Variables Reference. For variable types created by policies, refer to the
specific policy reference topic.
Example
var sap = require('sap-access');
// "httpRequest" must be a request object that came from the http module
var val1 = sap.getVariable(request, 'TestVariable');
var val2 = sap.getVariable(request, 'request.client.ip');
setVariable
Sets a variable. Some variables are read-only, and the setVariable() method throws an exception if you try to set
one of them. To determine which variables are read-only, see the Variables Reference.
Parameters:
• dhttpRequest: The request object that comes from the http module.
• name: (String) The name of the variable to retrieve.
• value: Can be a number, String, boolean, null, or undefined.
Example
var sap = require('sap-access');
sap.setVariable(request, 'TestVariable', 'bar');
// This will throw an exception because client.ip is read-only.
sap.setVariable(request, 'client.ip');
The setIntVariable() method is a convenience method that first coerces the value parameter to an integer,
and then sets it.
Parameters:
• httpRequest: The request object that comes from the http module.
• name: (String) The name of the variable to set.
• value: The value parameter must be a string or number.
Example
var sap = require('sap-access');
// Convert "123" to an integer and set it
sap.setIntVariable(request, 'TestVariable', '123');
// Use something that's already a number
sap.setIntVariable(request, 'TestVariable2', 42);
deleteVariable
Deletes a named variable. It is an error to delete a read-only variable. For a complete list of read-only variables,
see the Variables Reference.
deleteVariable(httpRequest, name);
Parameters:
• httpRequest: The request object that comes from the http module.
• name: (String) The name of the variable to delete.
Example
sap.deleteVariable(request, 'TestVariable');
// This will throw an exception because client.ip is a read-only variable.
sap.deleteVariable(request, 'client.ip');
The sap-access module lets you access the SAP API Management distributed cache from your Node.js code.
getCache
Parameters:
cache-name - The name of the cache to access.
Returns:
A cache object.
Example
var sap = require('sap-access');
var cache = sap.getCache('cache');
getCache
Parameters:
{parameter: 'value'} - (Optional) A configuration object. The object can be empty, or it can contain the following
optional parameters:
• resource: The name of an SAP API Management "cache resource" where the cache data is stored. Cache
resources are used to fine-tune memory allocation and other cache parameters. If not specified, a default
resource will be used. If the cache resource does not exist, then the method throws an error.
• scope: Specifies whether cache entries are prefixed to prevent collisions. Valid values are global, application,
and exclusive.
o global: All cache entries may be seen by all Node.js applications in the same SAP API Management
"environment."
o application: All cache entries may be seen by all Node.js caches that are part of the same SAP API
Management application.
o exclusive: (Default) Cache entries are only seen by Node.js caches in the same application that have
the same name. This is the default.
Returns:
A custom cache object.
Example
var sap = require('sap-access');
var customCache = sap.getCache('MyCustomCache',
{ resource: 'MyCustomResource'} );
put
Parameters:
• key: (Required) A string that uniquely identifies the item in the cache.
• data: (Required) A string, Buffer, or object that represents the data to cache. Any other data type will result in
an error. For convenience, objects will be converted into a string using "JSON.stringify".
• ttl: (Optional) The maximum time to persist the data in the cache, in seconds. If not specified then a default
TTL will be used.
• callback: (Optional) If specified, a function that will be called once the data is safely in the cache. It will be
called with an Error object as the first parameter if there is an insertion error, and otherwise it will be called
with no parameters.
Example
var sap = require('sap-access');
var cache = sap.getCache();
// Insert a string with a timeout of 120 seconds
cache.put('key2', 'Hello, World!', 120);
// Insert a string and get notified when insert is complete
cache.put('key4', 'Hello, World!', function(err) {
// "err" will be undefined unless there was an error on insert
});
Parameters:
• key (required): A string that uniquely identifies the item in the cache.
• callback (required): A function that will be called when the data is available. If there is cached data, it is
returned in the second parameter.
o error - An Error object. If there is an error while retrieving from the cache, then an Error object will be set
here. Otherwise this parameter will be set to "undefined".
o data - The data retrieved, if any. It will be one of four values:
o If a string was inserted, it will be a string.
o If a Buffer was inserted, it will be a Buffer.
o If an object was inserted, it will be a string containing the JSON version of the object as produced by
"JSON.stringify".
o If nothing was found, then it will be "undefined".
Example
var sap = require('sap-access');
var cache = sap.getCache();
cache.get('key', function(err, data) {
// If there was an error, then "err" will be set
// "data" is the item that was retrieved
// It will be a Buffer or a String depending on what was inserted.
});
remove
cache.remove('key', function(error));
Invalidate a cached item. Once a key is invalidated, subsequent get() requests will return "undefined" unless
another value is inserted.
Parameters:
• key (Required): A string that uniquely identifies the item in the cache to invalidate.
• callback (Required): A callback function that will be called with an Error object as the first parameter if there
is an error.
Example
var sap = require('sap-access');
var cache = sap.getCache();
cache.remove('key', function(err) {
The sap-access module lets you access the SAP API Management quota service from your Node.js code.
Methods
apply
Modifies the settings on a Quota object. Use this method to increment or decrement the quota, change time
intervals, and make other configurations.
Usage
var sap = require('sap-access');
var quota = sap.getQuota();
quota.apply({parameters}, callback);
Example
var sap = require('sap-access');
var quota = sap.getQuota();
function quotaResult(err, r) {
if (err) { console.error('Quota failed'); }
}
Parameters
The apply() method takes two parameters, an object and a function:
o identifier (string, required): A unique identifier of the quota bucket. In practice it might be an application
ID, IP address, or username.
o timeUnit (string, required): How long the quota bucket will accumulate until it is reset. Valid values are
"minute," "hour," "day," "week," and "month."
o allow (number, required): The maximum value for the quota bucket. This value will be combined with the
current value to return whether the quota has succeeded.
o interval (number, optional): Combined with the "timeUnit" to determine how long before the quota is
reset. The default is 1. Set to a larger value to allow quotas such as "two hours," "three weeks," and so on.
o weight (number, optional): The value to increment the quota by. Default is 1.
5. The second argument is a callback function with these two arguments:
o The first argument is an Error object if the quota cannot be incremented, or undefined if the operation
succeeded.
o The second is an object that contains the following fields:
o used (number): The current value of the quota bucket.
o allowed (number): The maximum value of the quota bucket before the quota is considered to be
exceeded. The same value was passed as "allow" in the request object.
o isAllowed (boolean): If there is room left in the quota -- true as long as "used" is less than or equal to
"allowed."
o expiryTime (long): The timestamp, in milliseconds since 1970 format, when the quota bucket will be
reset.
o timestamp (long): The timestamp at which the quota was updated.
Example
< var sap = require('sap-access');
var quota = sap.getQuota();
function quotaResult(err, r) {
if (err) { console.error('Quota failed'); }
}Put your example here>
reset
To reset the quota to zero, call quota.reset(). This method takes two parameters:
• A JSON object with these fields:
o identifier (string, required): A unique identifier of the quota bucket. In practice it might be an application
ID, IP address, or username.
o timeUnit (string, required): How long the quota bucket will accumulate until if it is reset. Valid values are
"minute," "hour," "day," "week," and "month."
o interval (number, optional): Combined with the "timeUnit" to determine how long before the quota is
reset. The default is 1. Set to a larger value to allow reset times such as "two hours," "three weeks," and so
on.
• A callback function:
o The callback takes an Error object as the first parameter if the reset fails.
The sap-access module lets you store sensitive data, such as passwords for backend services, in an encrypted
format on SAP API Management.
To support local development and testing, the SAP API Management-access module works in a "local mode" with
no dependencies on SAP API Management; however, when the module is used with an API proxy that is deployed
to SAP API Management, the "local" functionality is replaced by native SAP API Management functionality. For
example, the full compliment of flow variables are accessible in deployed mode, while only a small subset are
available when you run the Node.js application locally. For a list of these local-mode variables, see "Running in
local mode", below.
Again, on the SAP API Management platform, a much larger set of pre-defined variables is supported. Refer to the
Variables Reference for the complete list.
It's a good practice to make sure any Node.js code you add to a proxy works before you deploy it to SAP API
Management. This topic discusses ways to debug proxies that include Node.js applications after they are
deployed.
Note
The Node.js Logs button does not appear for non-Node.js API proxies.
In the Logs page, you can select a time range of logs to view, as shown below. The logs record HTTP method calls,
success or failure of calls, console.log messages, and so on. Enter a search string in the search field to display all
log entries that contain the string.
The trace tool is useful for general proxy debugging. For detailed information on using the trace tool, see Using the
Trace tool.
You can embed console.log statements in your Node.js code and view the output in the trace tool. For example,
the following statement prints the username of the user who is logging in to access the proxy:
console.log('Logging in as %s', config.username);
assert Supported
buffer Supported
domain Supported
events Supported
http Supported The virtual host and path for incoming requests is
specified in the API Proxy, not by the HTTP
module. See "Understanding support for the http
and https modules" for more information.
module Supported
path Supported
module Supported
punycode Supported
querystring Supported
module Supported
STDIO Supported Standard output and error are routed to a log file
within the SAP API Management infrastructure.
There is no standard input for scripts running on
SAP API Management. However, you can pass
arguments using the ScriptTarget element of
TargetEndpoint. See Advanced ScriptTarget
configuration for more information.
stream Supported
string_decoder Supported
timers Supported
url Supported
util Supported
vm Supported
zlib Supported
All Node.js applications running in SAP API Management must use the http or https module to listen for incoming
requests. If you were to deploy a script that doesn't listen for incoming requests, it would simply execute and exit.
The listen method of the http and https modules in Node.js takes a port number as a parameter. For example:
svr.listen(process.env.PORT || 9000, function() {
console.log('The server is running.');
});
This "port" argument is required in Node.js, but SAP API Management ignores this parameter. Instead, the API
proxy in which the Node.js script runs specifies the "virtual host" that it listens on, and the Node.js application
uses those same virtual hosts, just like any other SAP API Management proxy.
Every environment in SAP API Management has at least one virtual host. The virtual host defines the HTTP
settings for connection with the SAP API Management organization. All API proxies in an environment share the
same virtual hosts. By default, two virtual hosts are available for each environment: default and secure.
The SAP API Management tool deploynodeapp command generates an SAP API Management proxy wrapper
around the Node.js application. When deployed, the Node.js application listens on the default virtual host defined
for the environment.
SAP API Management supports the Node.js tls module. This module uses OpenSSL to provide Transport Layer
Security (TLS) and/or Secure Socket Layer (SSL) encrypted stream communication. You can use the tls module
to create secure connections to backend services from Node.js applications running on SAP API Management.
To understand how the tls module works on SAP API Management, it's important to understand how virtual hosts
are used on SAP API Management. Every environment in SAP API Management has at least one virtual host. The
virtual host defines the HTTP settings for connection with the SAP API Management organization. All API proxies
in an environment share the same virtual hosts. By default, two virtual hosts are available for each environment:
default and secure.
Now, let's look at how SAP API Management handles TLS (SSL) communication for incoming and outgoing
requests on Node.js applications:
SAP API Management does not support the "cluster" module, which allows Node.js applications to control when
additional copies of an application are started and stopped, and to communicate with them. In the parlance of the
"cluster" module, all Node.js applications are considered to be the "master."
However, SAP API Management does deploy multiple instances of each application — two in most cases, although
the system may be configured to run more if necessary.
That means that Node.js applications running inside SAP API Management, like all Node.js applications, must
assume that they will be processing many different requests "in parallel" using a single thread of control. However,
the application must not assume that it is the only copy running in the world, though it also must not assume that
there is some way to communicate with the other copies.
In the <TargetEndpoint> definition, the <ScriptTarget> element takes additional optional parameters
besides <ResourceURL>. You can also pass command-line arguments and environment variables to a Node.js
script using the <EnvironmentVariables> and <Arguments> parameters:
<TargetEndpoint name="default">
<ScriptTarget>
<ResourceURL>node://hello.js</ResourceURL>
<EnvironmentVariables>
<EnvironmentVariable name="NAME">VALUE</EnvironmentVariable>
</EnvironmentVariables>
<Arguments>
<Argument>ARG</Argument>
</Arguments>
</ScriptTarget>
</TargetEndpoint>
Trace is a tool for troubleshooting and monitoring API proxies running on SAP API Management. Trace lets you
probe the details of each step through an API proxy flow.
Trace is simple to use. You start a trace session and then make an API call to the SAP API Management, and read
the results.
1. Select API Proxies from the APIs menu.
2. Select an API proxy from the API Proxies page.
3. Be sure the API you wish to trace is deployed.
4. Choose Trace to go to the Trace tool view.
5. Use the Deployment to Trace dropdown menu to select which deployment environment and proxy revision
you wish to trace.
6. Choose Start Trace Session. When the Trace session is active, the API proxy records details of each step in
the processing pipeline. While the Trace session is running, messages and contextual data are captured from
live traffic.
Note
One Trace session can support 10 request/response transactions through the selected API proxy. If there
are 2 per router, then 20 request/response transactions are supported. Trace sessions automatically
stop after 10 minutes if you don't manually stop it.
8. When you've captured a sufficient number of requests, choose Stop Trace Session.
9. A list of captured request/response transactions displays in the left menu. Choose on any of the transactions
to view detailed results.
To read a trace, just follow the arrows: the request flow steps are shown along the top and response flow steps
along the bottom of the map.
The tool's transaction map uses icons to mark each notable step that occurs during an API proxy transaction,
including policy execution, conditional steps, and transitions. Hover over any icon to see summary information.
The phase details section of the tool lists information about the proxy's internal processing, including variables
that were set or read, request and response headers, and much more. Choose any icon to see the phase
details for that step.
Here's a sample trace tool map with the main proxy processing segments labeled:
Any good map needs a legend. The following table describes the intent of the icons you will see in the transaction
map. These icons mark each of the notable processing steps throughout the proxy flow.
Transaction map icons
The client app that sends a request to the ProxyEndpoint of the API proxy.
The circles mark transitional endpoints in the proxy flow. They are there when a request
comes in from the client, when the request goes to the target, when the response
comes back from the target, and when the response goes back to the client.
The tall bars indicate the beginning of a flow segment in the API proxy flow. Flow
segments are: ProxyEndpoint request, TargetEndpoint request, TargetEndpoint
response, and ProxyEndpoint response. A segment includes the PreFlow, Conditional
Flows, and PostFlow.
See Flows Configuration for more information.
The short bars are called "executions." You'll see these bars when Analytics actions
occur in the background. Hover over these bars to see what kind of data is being stored
in Analytics.
A policy. Each type of policy has a unique icon. This one is for the AssignMessage
policy. These icons let you see where policies are executed in the proper order and if
they are successful or not. You can choose a policy icon to see the results of its
execution and if they are expected or not. For example, you can see if the message was
transformed properly or if it is being cached.
Properly executing policies are clearly indicated by check-marks. In the case of an
error, a red exclamation mark is displayed on the icon.
Tip: Pay attention to the tooltip or the time line to see if any policy is taking longer than
expected.
Disabled. Appears on a policy icon when a policy is disabled. A policy can be disabled
with the public API. See API proxy configuration reference.
Error. Appears on a policy icon when the Policy Step condition evaluates to false
(see Flow Variables and Conditions), or on the RaiseFault policy icon whenever a
RaiseFault policy executes.
Skipped. Appears on a policy icon when the policy was not executed because the step
condition evaluated to false. See Flow Variables and Conditions for more information.
The Phase Details part of the tool tells you a lot about the state of your proxy at each processing step. Here are
some of the details provided in the Phase Details. Choose any icon in the trace tool to see details for the selected
step, or use the Next/Back buttons to move from one step to another.
Note
Trace captures message content. If your message payloads contain sensitive information, then you
should enable data masking. For instructions, see Data masking.
Variables Read Lists the flow variables that were read by a policy.
See also Introduction to Flow Variables.
Variables Read and Assigned Lists the flow variables that were read and assigned a
value by a policy.
Trace lets you see a lot of internal details about an API proxy. For example:
• You can see at a glance which policies are executing correctly or failing.
• Let's say you noticed through one of the Analytics dashboards that one of your APIs is experiencing an
unusual decrease in performance. Now, you can use Trace to help identify where the bottleneck is occurring.
Trace gives the time, in milliseconds, which it takes for each processing step to complete. If you find one step
is taking too long, you can take corrective action.
• By looking at the phase details, you can check headers that are being sent to the backend, view variables set
by policies, and so on.
• By verifying the base path, you can ensure that a policy is routing the message to correct server.
Show Disabled Policies Show any disabled policies. A policy can be disabled
with the public API. See API proxy configuration
reference.
Show Skipped Phases Show any phases that were skipped. A skipped phase
occurs when policy was not executed because the
step condition evaluated to false. See Flow Variables
and Conditions for more information.
Automatically Compare Selected Phase Compares the selected phase to the previous one.
Turn this off to see only the selected phase.
You can download an XML file of the trace results for viewing offline. The file shows the complete details of the
listening session including the contents of all headers, variables and policies.
To download raw trace output, choose Download Trace Session.
The Offline Trace tool lets you view and analyze trace sessions that were previously saved. A saved trace session
is essentially a "recording" of a trace session, and can be useful for cases where troubleshooting and further
analysis is required. The UI for the Offline Trace tool is similar to the "live" Trace tool. To learn about the Trace
Tool UI and on saving trace sessions, see Using a Trace tool.
1. Select APIs > API Proxies from the main SAP API Management menu.
2. On the API Proxies page, choose Offline Trace.
In the Offline Trace tool, choose Choose File and select a downloaded trace file from your system.
Troubleshooting
To enable root-case analysis, filters enable you to target specific calls that may be causing problems. For
example, you may need to zero in on requests that have specific content or requests coming from specific
partners or apps.
• HTTP headers - limits the trace to only calls that contain a specific header. This is a good way of helping you
troubleshoot issues. You can send a header to your app developer and ask them to include it in the call that is
To add a filter:
1. Open the Filter section of the Trace page.
2. Enter a name and value into either the Header or Query fields. Blank fields are not evaluated.
You can add more filters by choosing the Add Filter button. You can delete filters by choosing the (X) button
next to the filter.
Because the management API is RESTful, response messages can be interpreted as a combination of an HTTP
response code and an SAP API Management -specific error message.
For example, if you try to create a company entity with the same name as an existing company, the response is:
404
{
"code": "messaging.config.beans.ApplicationDoesNotExist",
"message": "APIProxy named WeatherApi does not exist in organization mycompany",
"contexts": []
}
An explanation of important HTTP response codes follows:
SAP API Management provides a "history" feature that can be helpful in troubleshooting problems as well as
managing API usage. The history feature enables you to view the operations (create, update, read, delete, deploy,
undeploy) that have been performed on your APIs and API products over time. You can see who performed each
operation, when the operation was performed, the request URI, and the response code. For update operations,
you can also view the request body that was as passed in the API call.
3. You can change the date range for the history to the last day, week, 2 months, 3 months, or year, by selecting
from the menu next to "Showing data for last".
2. You can change the date range for the history to the last day, week, 2 months, 3 months, or year, by selecting
from the menu next to Date Range.
3. You can view the request body for update operations by choosing Show in the Request Body column for the
operation.
When you don't want to use the included shared cache, you can create and configure your own cache. You can use
the cache you create beneath caching policies, rather than using the the shared cache.
Note
Under ordinary circumstances, you don't need to configure your own cache. Only configure a cache when
you need to customize the cache settings and optimize performance.
You can create multiple cache resources in each environment. When you're configuring a caching policy, you
specify whether the policy should use the included shared cache or a cache you created.
For data segregation, the scope of a cache is limited to the environment in which you created the cache. (For
example, API proxies running in a 'test' environment cannot access data in a cache running in 'prod'.) Once you
create a cache, policies can populate it with any serializable data.
These steps describe how to create or edit a cache using the management console.
1. In the management UI, choose the APIs menu, then choose Environment Configuration.
2. In the Environment dropdown, select the environment for which you want to configure caches, such as test
or prod.
3. Go to the Caches tab.
4. Choose Edit.
5. Under Caches, at the right side, choose the +Cache button to add a new cache.
The button displays the New Cache dialog.
6. In the New Cache form, enter property values for the new cache. The following table describes the settings.
Property Default
Description Notes
Name Value
Expiration Timeout in Sets how cache entries will be expired. Populate Cache
Type Seconds Entry time to live can be a specified policyand Response Cache
number of seconds after creation, a policy both override these
specified time of day each day, or a expiration settings with their
specified date. own for cache entries they
create.
7. Choose Save.
There are often situations where you want to store key/value pairs of data for longer term and access that data at
runtime with your API proxies.
For example, you could store the latitude and longitude of a location of a conference (using key names like conLAT
and conLON), retrieve those keys in an API proxy call, and pass the latitude and longitude data into the message
body of the request or response (or to a mapping API). And if the location of the conference happened to change
the following year, all you would have to do is update the values without having to touch your API proxy logic,
which gets the data using the same key names.
You store one or more key/value pairs of data in a grouping called a 'map', or 'key/value map'.
Caution:
Key/value maps aren't designed to store sensitive data such as usernames and passwords.
There may be different scopes at which you want to store key/value data. For example, if only one API proxy
requires data in a key/value map, you can create the key/value map at the API proxy scope, where only that API
proxy can access the data. Or you may want all API proxies in your test environment to have access to a key/value
map, in which case you'd create a key/value map at the environment scope.
Note:
When creating and managing key/value maps in the management UI, which this topic covers, you're creating
them at the environment scope.
or information about how to create and manage key/value maps at other scopes, such as organization or proxy
scopes (as well as the environment scope), see the following topics:
Management API: Persist Data Using KeyValueMap.
Policy: Configuring the KeyValueMapOperation Policy. The policy is also how you access key/value data at
runtime.
These steps describe how to create or edit a key/value map in the management UI. Key/value maps created this
way are at the environment scope. For example, if you create a key/value map in the 'test' environment, API
proxies running in the 'prod' environment won't have access to the key/value map.
1. In the management UI, select APIs > Environment Configuration.
2. Select the environment for which you want to configure key/value maps, such as test or prod.
3. Go to the Key Value Maps tab.
4. Click +Key Value Map to create an new one, or expand an existing key/value map and click Edit.
5. Click the +Entry button to add a new key/value pair.
Key N/A The key name that you'll use to access the data value in
your API proxies.
In organizations with Core Persistence Services (see
below), key names cannot be larger than 2 KB.
Value N/A The value of the key. Enter any combination of numbers,
letters, or special characters. There is no size limitation.
7. Choose Save.
To view or modify maps with more than 150 keys, the UI directs you to use the SAP API Management's API.
SAP API Platform enhances the availability of your API by providing built-in support for load balancing and failover
across multiple backend server instances.
TargetServer configurations decouple concrete endpoint URLs from TargetEndpoint configurations. Each
TargetServer is referenced by name in a TargetEndpoint HTTPConnection. Instead of defining concrete URL in the
configuration, you can configure one or more named TargetServers.
A TargetServer definition consists of a name, a host and a port, with an additional element to indicate whether the
TargetServer is enabled or disabled.
You can use the SAP API Management Edge UI to create and manage target servers.
For example:
• Name: target1
• Host: 1.mybackendservice.com
• Port: 80
• Enabled: Selected
Repeat these steps to add and enable more target servers.
You can use Edge management APIs to create, delete, update, get, and list target servers. For more information,
see TargetServers.
$ curl -H "Content-Type:text/xml" -X POST -d \
'<TargetServer name="target1">
<Host>1.mybackendservice.com</Host>
<Port>80</Port>
<IsEnabled>true</IsEnabled>
</TargetServer>' \
-u email:password
https://<managment_server_ip:8080>/v1/o/{org_name}/environments/test/targetservers
Sample Response:
{
"host" : "1.mybackendservice.com",
"isEnabled" : true,
"name" : "target1",
"port" : 80
}
After you create the first TargetServer, then create a second TargetServer. By defining two TargetServers, you
provide two URLs that a TargetEndpoint can use for loadbalancing:
Sample Response:
{
"host" : "2.mybackendservice.com",
"isEnabled" : true,
"name" : "target2",
"port" : 80
}
Retrieve a list of TargetServers in an environment:
$ curl -u email:password
https://<managment_server_ip:8080>/v1/o/{org_name}/environments/test/targetservers
Sample response:
[ "target2", "target1" ]
There are now two TargetServers available for use by API proxies deployed in the test environment. To load
balance traffic across these TargetServers, you configure the HTTP connection in an API proxy's target endpoint
to use the TargetServers.
There is no limit on the number of TargetServers that you can set up in an environment or reference from a
TargetEndpoint
Now that you have two TargetServers available, you can modify the TargetEndpoint HTTP connection setting to
reference those two TargetServers by name.
<TargetEndpoint name="default">
<HTTPTargetConnection>
<LoadBalancer>
<Server name="target1" />
<Server name="target2" />
</LoadBalancer>
<Path>/test</Path>
</HTTPTargetConnection>
</TargetEndpoint>
Note
Retries are triggered by I/O exceptions and HTTP time outs. Retries are not triggered by HTTP error
codes (4xx, 5xx).
You can tune availability by using options for load balancing and failover at the load balancer and TargetServer
level.
Available options for LoadBalancers are:
Algorithm
Sets the algorithm used by LoadBalancer. The available algorithms are RoundRobin, Weighted, and
MaximumFailures, each of which is documented below.
Round robin
The default algorithm,RoundRobin forwards a request to each TargetServer in the order in which the servers are
listed in the target endpoint HTTP connection.
For example:
<TargetEndpoint name="default">
<HTTPTargetConnection>
<LoadBalancer>
<Algorithm>RoundRobin</Algorithm>
<Server name="target1" />
<Server name="target2" />
</LoadBalancer>
<Path>/test</Path>
</HTTPTargetConnection>
</TargetEndpoint>
Weighted
The weighted load balancing algorithm enables you to configure proportional traffic loads for your TargetServers.
The weighted LoadBalancer distributes request to your TargetServers in direct proportion to each TargetServer's
weight. Therefore, the weighted algorithm requires you to set a weight attribute for each TargetServer. For
example:
<TargetEndpoint name="default">
Least Connection
LoadBalancers configured to use the least connection algorithm route outbound requests to the TargetServer
with fewest open HTTP connections.
<TargetEndpoint name="default">
<HTTPTargetConnection>
<LoadBalancer>
<Algorithm>LeastConnection</Algorithm>
<Server name="target1" />
<Server name="target2" />
</LoadBalancer>
</HTTPTargetConnection>
<Path>/test</Path>
</TargetEndpoint>
Maximum Failures
The maximum number of failed requests from the API proxy to the TargetServer that results in the request being
redirected to another TargetServer. As configured below, target1 will be removed from rotation after 5 failed
requests.
<TargetEndpoint name="default">
<HTTPTargetConnection>
<LoadBalancer>
<Algorithm>RoundRobin</Algorithm>
<Server name="target1" />
<MaxFailures>5</MaxFailures>
Note
If you configure MaxFailures without also configuring a HealthMonitor, then eventually all of your
TargetServers will be removed from rotation. If you configure MaxFailures, always configure an
associated HealthMonitor.
The MaxFailures default is 0. This means that SAP API Management Edge always tries to connect to the
target for each request and never removes the target server from the rotation.
Retry
Retry the request once to a different server after an I/O error (not an HTTP status code 500).
<RetryEnabled>true</RetryEnabled>
IsFallback
One (and only one) TargetServer can be set as the 'fallback' server. The fallback TargetServer is not included in
load balancing routines until all other TargetServers are identified as unavailable by the load balancer. When the
load balancer determines that all TargetServers are unavailable, all traffic is routed to the fallback server. For
example:
<TargetEndpoint name="default">
<HTTPTargetConnection>
<LoadBalancer>
<Algorithm>RoundRobin</Algorithm>
<Server name="target1" />
<Server name="target2" />
<Server name="target3" />
<IsFallback>true</IsFallback>
</LoadBalancer>
<Path>/test</Path>
</HTTPTargetConnection>
</TargetEndpoint>
The configuration above results in round robin load balancing between targets 1 and 2 until both targets 1 and 2
are unavailable. When targets 1 and 2 are unavailable, all traffic is routed to target 3.
Path
Path defines a URI fragment that will be appended to all requests issued by the TargetServer to the backend
server.
If you are using a TargetServer to define the backend service, and the backend service requires the connection to
use the HTTPS protocol, then you must enable SSL in the TargetServer definition. This is necessary because
the <Host> tag does not let you specify the connection protocol. Shown below is the TargetServer definition for
one-way SSL where SAP API Management Edge makes HTTPS requests to the backend service:
<TargetServer name="target1">
<Host>weather.yahooapis.com</Host>
<Port>443</Port>
<IsEnabled>true</IsEnabled>
<SSLInfo>
<Enabled>true</Enabled>
</SSLInfo>
</TargetServer>
If the backend service requires two-way, or mutual, SSL, then you configure the TargetServer by using the same
SSL configuration settings as TargetEndpoints:
<TargetServer name="TargetServer 1">
<IsEnabled>true</IsEnabled>
<Host>www.example.com</Host>
<Port>443</Port>
<SSLInfo>
<Ciphers/>
<ClientAuthEnabled>true</ClientAuthEnabled>
<Enabled>true</Enabled>
<IgnoreValidationErrors>false</IgnoreValidationErrors>
<KeyAlias>keystore-alias</KeyAlias>
<KeyStore>keystore-name</KeyStore>
<Protocols/>
<TrustStore>truststore-name</TrustStore>
</SSLInfo>
</TargetServer >
For information on the <SSLInfo> properties, such as <Ciphers>, <ClientAuthEnabled>, etc., see the information
on setting those properties for a Virtual Host.
For complete instructions on configuring outbound SSL, see Configuring SSL to the Backend Service.
Health monitoring enables you to enhance load balancing configurations by actively polling the backend service
URLs defined in the TargetServer configurations. The HealthMonitor acts as a simple client that invokes a
backend service over TCP or HTTP. A TCP client simply ensures that a socket can be opened. You configure the
HTTP client to submit a valid HTTP request to the backend service. You can define HTTP GET, PUT, POST, or
DELETE operations. Typically, you define a simple GET request that simply shows that the backend service is
available.
You create a HealthMonitor by setting one up in a TargetEndpoint's HTTPConnection configuration. A simple
HealthMonitor defines an IntervalInSec combined with either a TCPMonitor or an HTTPMonitor.
TCPMonitor
The configuration below defines a HealthMonitor that polls each TargetServer by opening a connection on port 80
every 5 seconds.
• If the connection fails or takes more than 10 seconds to connect, then the failure count increments by 1 for
that TargetServer.
• If the connection succeeds, then the failure count for the TargetServer is reset to 0.
You can add a HealthMonitor as a child element of the TargetEndpoint's HTTPTargetConnetion element, as
shown below:
<TargetEndpoint name="default">
<HTTPTargetConnection><HealthMonitor>
<IsEnabled>true</IsEnabled>
<IntervalInSec>5</IntervalInSec>
<TCPMonitor>
<ConnectTimeoutInSec>10</ConnectTimeoutInSec>
<Port>80</Port>
</TCPMonitor>
</HealthMonitor>
HTTPMonitor
A sample HealthMonitor that uses an HTTPMonitor will submit a GET request to the backend service once every
five seconds. The sample below adds an HTTP Basic Authorization header to the request message. The Response
configuration defines settings that will be compared against actual response from the backend service. In the
example below, the expected response is an HTTP response code 200 and a custom HTTP header ImOK whose
value isYoureOK. If the response does not match, then the request will treated as a failure by the load balancer
configuration.
Note
All of the Request and Response settings in an HTTP monitor will be specific to the backend service that
must be invoked.
<HealthMonitor>
<IsEnabled>true</IsEnabled>
<IntervalInSec>5</IntervalInSec>
<HTTPMonitor>
<Request>
<ConnectTimeoutInSec>10</ConnectTimeoutInSec>
<SocketReadTimeoutInSec>30</SocketReadTimeoutInSec>
<Port>80</Port>
<Verb>GET</Verb>
<Path>/healthcheck</Path>
<Headers>
<Header name="Authorization">Basic 12e98yfw87etf</Header>
</Headers>
</Request>
<SuccessResponse>
<ResponseCode>200</ResponseCode>
<Headers>
<Header name=”ImOK”>YoureOK</Header>
</Headers>
</SuccessResponse>
</HTTPMonitor>
</HealthMonitor>
Virtual Hosts
Virtual hosts let multiple domain names connect to the same host. A virtual host on SAP API Management defines
the domains and Router ports on which an API proxy is exposed, and, by extension, the URL that apps use to
access an API proxy. A virtual host also defines whether the API proxy is accessed by using the HTTP protocol, or
by the encrypted HTTPS protocol. In SAP API Management Edge, a virtual host is identified by a name. By default,
when you first create an SAP API Management Edge organization, you get two virtual hosts in each environment:
• default - http://[org]-[environment].sap.net (port 80)
• secure - https://[org]-[environment].sap.net (port 443)
https://myorg-prod.<host>:<port>/v1/{proxy-base-path}/{resource-path}
However, a domain name containing "host:port" may not be what you want to expose to your customers. A virtual
host can map your own domain name to your organization, letting developers access your API through a domain
specific to your company, for example:
https://api.myCompany.com/v1/{proxy-base-path}/{resource-path}
Note that creating a virtual host does not also make the domain name accessible. You must still create a DNS
record for the domain.
There are no default organizations, environments, or virtual hosts created for you. After you complete the SAP
API Management installation process, your first action is typically to create an organization, environment, and
virtual host through the "onboarding" process.
Note:
To perform onboarding, please check section 3.7 Onboard an Organization topic in the SAP API Management
Installation Onboarding Guide.
For example, if you use the default values in the setup-org.sh script, you create:
• A user of your choosing to function as the organization administrator
• An organization named example
• An environment in the organization named prod
• A virtual host in the environment named default that allows HTTP access on port 9001
• No host alias
After running the onboarding script, you can later add any number of organizations, environments, and virtual
hosts to your installation.
Virtual hosts are opened on the Router node. Therefore, you have to ensure that the port that you specify for the
virtual host is open on the Router node. You can use a command in the form below to open a port:
$ iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 9001 -j ACCEPT --
verbose
http://<router-ip>:9001/{proxy-base-path}/{resource-path}
Note that this URL uses the IP address of the Router and the virtual host port on the Router to access your APIs.
Typically, you do not publish your APIs to customers with an IP address and port number. Instead, you define a
DNS entry for the router and port. For example:
http://myAPI.myCo.com/{proxy-base-path}/{resource-path}
If you define the DNS entry, then you also must create a host alias for the virtual host that matches the domain
name of the DNS entry. From the example above, you would specify a host alias of myAPI.myCo.com when you
create the virtual host.
Note also that the URL uses the HTTP protocol. To use the encrypted HTTPS protocol, you must create a virtual
host that references a keystore. A keystore contains the certificate and private key required to support HTTPS.
You can use the SAP API Management UI to see the virtual hosts defined in an environment:
1. Login to the management UI at http://<ms-ip>:9000 , where <ms-ip> is the IP address of the Management
Server node.
2. In the management UI menu, select APIs > Environment Configuration.
3. Select the environment, such as prod or test. The virtual hosts defined for the environment appear.
If the virtual host is configured to use a keystore or truststore, select the Show button to see more
information.
You can also use the SAP API Management APIs to view information about virtual hosts. For example, the List
Virtual Hosts API returns a list of all virtual hosts:
Sample response:
[
To see information about a specific virtual host, use the Get Virtual Host API:
Sample response:
{
"hostAliases" : [sapdocs-prod.<host:port> ],
"interfaces" : [ ],
"name" : "default",
"port" : "9001"
}
If the virtual host is configured to use SSL, a lock icon appears next to the name of the virtual host. That means an
SSL certificate, key, and certificate chain has been uploaded to SAP API Management and associated with the
virtual host.
To see information about the available certificates:
1. Login to the management UI.
2. In the SAP API Management UI menu, select Admin > SSL Certificates.
3. Expand the keystores until you see the certificate.
An API proxy references the virtual hosts that it supports in its ProxyEndpoint definition. When you create a new
API proxy, SAP API Management automatically configures its ProxyEndpoint to use all available virtual hosts.
After SAP API Management notifies you that your new virtual host has been created, any new API proxies that you
create automatically reference the virtual host.
Note
If you create a new API proxy that should not be accessible over a particular virtual host, then you must
edit the API proxy to remove that virtual host from its ProxyEndpoint.
If you created any API proxies before requesting the virtual host, then you must edit the API proxy to add the new
virtual hosts to its ProxyEndpoint. Otherwise, the API proxy is not accessible by the virtual host.
If you are developing your API proxies in XML, edit the XML file for the ProxyEndpoint to add or remove a virtual
host.
<HTTPProxyConnection>
<BasePath>/oauth10a/client_credential</BasePath>
<VirtualHost>default</VirtualHost>
<VirtualHost>secure</VirtualHost>
<VirtualHost>MyVirtualHost</VirtualHost>
</HTTPProxyConnection>
7. Save the API proxy. If the API proxy has been deployed, saving it redeploys it with the new setting.
Organization users are given explicit permission by the organization administrator to create, read, edit, and/or
delete entities in an SAP API Management organization. Permissions are role-based, where a role conveys a
specific, targeted set of permissions. This permission scheme is also called role-based access control, or RBAC
for short.
Organization users are typically members of your API team who develop and test APIs, run reports, and perform
other API admin tasks. Do not confuse organization users with app developers, the consumers of your APIs. The
process of onboarding app developers and managing their access to your APIs is an entirely separate topic.
Also, note that topic applies to API management, not API BaaS, which has its own user management framework.
Organization users can interact with the following entities. The degree of interaction permitted depends on the
role or roles that are assigned to the user by the organization administrator.
• API proxies
• API products
• Developer apps
• Developers
• Environments (Trace tool sessions and deployments)
• Custom reports (Analytics)
Before you and your team can start using SAP API Management, you need to have an account and an
organization. Once you have an account and an organization, if you're an administrator, you have access to the
Admin tab where you can add and modify users. As part of adding or modifying users, you set the user's role.
The Organization Users table on the Admin > Organization Users page lists all of the users attached to the
current organization. For each user you can see:
Note
By default, all users associated with an organization can view details about other organization users, such
as email address, first name, and last name. Only users with the Organization Administrator role can add
or update other organization users.
• Name: The name of the user you entered when you created the user.
• Primary email: The email address you entered when you created the user.
• Role: The role of the user, which determines the degree of access. By default, all users have a user role that
gives them full access to all features in SAP API Management.
Adding Users
Users of API Platform are members of the API team who develop and test the API, or run reports—not external
developers. To add an organization user:
1. In the SAP API Management management UI, while logged in as an organization administrator, select Admin
> Organization Users.
2. Choose + User. The "Add a User" screen appears.
3. Enter the user's First Name, Last Name, and Email.
4. Select the Role you want to offer to the users.
5. Choose Save.
The First Name, Last Name, and Email Address fields are editable, so if needed, you can change what you initially
entered for the user. You can also change the role selection if needed.
You can add one or more roles to a user when you create a new user or if you edit an existing user.
Note
If a user has multiple roles assigned, the greater permission takes precedence. For example, if one role
doesn't allow the user to create API proxies, but another role does, then the user can create API proxies.
In general, it is not a common use case to assign users multiple roles.
Note
This only removes the user from the current account. If the user is a member of multiple accounts, they
remain in the system.
An org admin can edit the first name, last name, and email address fields in the management UI.
Administrators can also change the user's role.
Assign Roles
This topic discusses role-based access control for SAP API Management organizations and explains how to create
roles and assign users to them. You must be an organization administrator to perform the tasks described here.
Roles are essentially CRUD-based permission sets. CRUD means "create, read, update, delete". For example, a
user may be given a role that permits her to read or "get" details about a protected entity, but not permission to
update or delete it. The organization administrator is the highest-level role, and can perform any CRUD operation
on protected entities, which include:
• API proxies
• API products
• Developer apps
• Developers
• Environments (Trace tool sessions and deployments)
• Custom reports (Analytics)
Getting started
In SAP API Management, user roles form the basis of role-based access, meaning that you can control what
functions a person can access by assigning them a role (or roles). Here are a few things you need to know about
roles:
Each SAP API Management Edge organization comes with a few built-in roles that you can assign to
administrative users:
• Organization Administrator - Super user. Has full CRUD access to resources in the organization. In an SAP
API Management Edge installation, the most powerful role is the System Administrator Role, which also has
access to system-level functions that the Organization Administrator doesn't.
• Read-only Organization Administrator - Has read-only access to resources in the organization.
• Operations Administrator - Deploys and tests APIs; has read-only access to other resources.
• Business User - Creates and manages API products, developers, developer apps, and companies; creates
custom reports on API usage; has read-only access to other resources.
• User - Creates API proxies and tests them in the test environment; has read-only access to other resources.
The built-in roles control the level of access in both the management UI and the management API.
To see the permissions set for each built-in role (as an Organization Administrator or a Read-only Organization
Administrator), select Admin > Organization Roles > name_of_role in the management UI.
For more information about how resource paths map to permissions, see "About permission setting" in Creating
roles with the API.
When a Developer Portal is provisioned for you, another role is added to your organization called Developer
Administrator. This role, which includes a single user called devadmin+{org_name}@apigee.com, is solely for the
purpose of connecting your Developer Portal to your SAP API Management Edge organization. Because the portal
displays your SAP API Management Edge developer apps, API products, and so on, it must stay in sync with your
SAP API Management Edge organization by making management API calls that require authentication. The
devadmin "user" has the necessary permissions.
You can add one or more roles to a user when you create a new user or if you edit an existing user.
Note
If a user has multiple roles assigned, the greater permission takes precedence. For example, if one role
doesn't allow the user to create API proxies, but another role does, then the user can create API proxies.
In general, it is not a common use case to assign users multiple roles.
1. Select Admin > Organization Users.
2. Either choose + User or choose an existing user.
3. Choose in the Roles field, and a dropdown appears.
4. Select a role to add.
5. Repeat steps 3 and 4 to add additional roles to the user if you want.
SAP API Management provides a set of default roles, out-of-the-box, and they are listed below.
• Business user
• Operations administrator
• Organization administrator
• User
The table shows you the levels of protection for resources. In this context, resources refer to "entities" that users
can interact with through the SAP API Management UI and API.
• The first column lists the general names of resources that users interact with. It also includes some other
things like API Proxies, Products, Deployments, etc. This column reflects the names of things as you see them
in the management UI.
• The second column lists the paths used to access resources through the management API.
• The third column lists the operations the role can perform on each resource and path. The operations are
GET, PUT, and DELETE. In the UI, these same operations are referred to as View, Edit, and Delete. Just keep in
mind that the UI and API uses different terms for these operations.
You can assign roles through management APIs or through the management UI. Either way, you're working with
CRUD permissions, although the API and UI use slightly different terminology.
The management UI refers to the same CRUD operations, but with different wording:
• View: Enables a user to view protected resources. Typically, you can view resources one at a time, or view a
list of resources.
• Edit: Enables a user to update a protected resource.
• Create: Enables a user to create a protected resource.
• Delete: Enables a user to delete an instance of a protected resource. Note: You can only delete a specific
instance of a resource. You cannot, for example, delete ALL API proxies, only a specific one.
Custom roles let you apply fine-grained permissions to these SAP API Management entities such as API proxies,
products, developer apps, developers, and custom reports.
This topic explains how to create custom roles in the management UI. Only an organization administrator can
create custom roles. Custom roles allow the admin to fine-tune which permissions to grant on specific resources.
For example, you can create a custom role that only grants users permission to view certain resources.
Note
SAP API Management also includes a set of pre-defined roles. For an introduction to roles and the
permissions granted to roles, see Manage users and roles. We recommend that you review that topic
before creating custom roles.
You can create custom roles to fine-tune access to these SAP API Management entities:
• API proxies
• API products
• Developer apps
• Developers
• Environments (Trace tool sessions and deployments)
• Custom reports (Analytics)
You can achieve even more granularity by applying role based access to specific instances of an entity. For
example, you can apply role-based access to all API products or to specific ones.
Precedence
More granular permissions take precedence over less granular ones. For example, permissions applied to a
specific developer app take precedence over a less-granular permission applied to all developer apps.
You can set some custom role permissions on an entity as a collection (e.g., all API products) or on a single
instance of an entity (e.g., one specificproduct).
If you set permissions on an instance, a privileged user can perform the permitted operations on that instance
only. If set on a collection (e.g., all API proxies), the user can perform the operations on any instance in the
collection.
You can also enable deploy and trace options on both collections and instances of APIs and caches. These
operations are also environment specific. That is, you can allow a role to deploy only to the prod environment.
An org administrator can create custom roles through the management UI.
1. Go to Admin > Organization Roles.
2. Choose + Custom Role.
3. Use the New Custom Role dialog to create the custom role.
This topic discusses how to create custom roles and assign roles to users through the management API. We also
show how to test role assignments through the API.
Create a 'development' role to enable developers to view, create, and update API proxies.
The permissions that can be set on collections are GET and PUT.
The permissions that can be set on individual members of a collection are GET, PUT, and DELETE. For the
'development' role, we add GET and PUT permissions on APIs. GET enables users to view any APIs, including API
proxy configuration files, associated policies, Javascript, XSLT files, and so on. The PUT permission on APIs
enables developers to create, modify, import, export, deploy and undeploy API proxies.
The path attribute specifies the resource on which you set the permissions. For example, /applications, /apps,
/apiproducts, /developers, or /reports.
Create a 'testing' role to enable quality engineers to view API proxies and their contents (including, for example,
policies).
GET enables users to view any APIs, including their configuration files, as well as any associated policies,
JavaScript, XSLT files, and so on. By adding this permission to the 'testing' role, we enable quality engineers to
view the contents of the APIs that they are testing. Users in this role will not, however, be able to create, modify,
import, export, deploy and undeploy API proxies.
$ curl -u myname:mypass
https://<host:port>/v1/o/{org_name}/userroles/testing/permissions -H "Content-
type:application/json" -X POST -d'{"path" : "/applications","permissions" : [ "get"
]}'
The minimum set of permissions that have to be set to allow the user to log in to the SAP API Management UI are:
$ curl -u myname:mypass
https://<host:port>/v1/o/{org_name}/users/[email protected]/userroles -H "Content-
type:application/json" -X POST -d'{"role" : [ {"name" : "testing"} ] }'
Impersonate the user and make a request to API Services to view API proxies. The user should be able to view
APIs, along with their contents.
Impersonate the user and make a request to API Services to create an API proxy. The request will be rejected by
API Services, as the role 'testing' does not permit the user to create APIs.
$ curl -u myname:mypass
https://<host:port>/v1/o/{org_name}/users/[email protected]/userroles -H "Content-
type:application/json" -X POST -d'{"role" : [ {"name" : "development"} ] }'
Impersonate the user and repeat the request to the API Platform to create an API proxy. The request will be
successful, as the role 'development' does permit the user to create APIs.
As an organization administrator, you can check the list of user roles for a user at any time:
$ curl -u myname:mypass
https://<host:port>/v1/o/{org_name}/users/[email protected]/userroles
This topic offers a basic overview of OAuth 2.0 on SAP API Management.
OAuth 2.0
There are many books, blogs, and sites devoted to OAuth 2.0. We highly recommend that you begin by reviewing
the IETF OAuth 2.0 specification. Here's the definition of OAuth 2.0 from the OAuth 2.0 IETF specification itself:
"The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP
service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner
and the HTTP service, or by allowing the third-party application to obtain access on its own behalf."
The main thing you need to know is that OAuth 2.0 provides a way for apps to gain limited access to a user's
protected resources (think of bank account or any other sensitive information a user might wish to access from an
app) without the need for the user to divulge her login credentials to the app.
Note
Let's say you found an app that lets you access multiple bank accounts. Maybe the app is used to help
with your taxes, or for managing your budget. You have three bank accounts that you want to manage
with the app, and you have a different username and password for each one. Now, for the app to access
your bank accounts, it needs those sensitive credentials. Basically, you're giving this sensitive information
to the app. Do you trust the app to possess your passwords and usernames? What if the app is hacked?
Now, you've got to remember change your bank credentials for each account. This is the fundamental
problem that OAuth 2.0 solves. Read on to learn how.
Here is the general flow for the OAuth 2.0 security framework. We'll discuss this flow in more detail in this topic,
starting with a diagram, which illustrates a lot about how OAuth 2.0 works. If you're unfamiliar with the terms used
in this diagram, read this section for a quick introduction.
You can protect any API proxies through SAP API Management with OAuth 2.0. It includes an authorization server
implementation, and as such, can generate and validate access tokens. Developers begin by registering their
apps with SAP API Management. Registered apps can request access tokens through any of the four grant
type interactions.
SAP API Management provides a multi-faceted OAuthV2 policy that implements the details of each grant type,
making it relatively easy to set up OAuth on SAP API Management. For example, you can configure a policy that
receives a request for an access token, evaluates all required credentials, and returns an access token if the
credentials are valid.
If you want to see how it fits together, check out the end-to-end tutorial. The tutorial steps through the process of
configuring the OAuth 2.0 policy, requesting an access token, and calling a protected API.
Note that any resource servers that your secure API proxy calls should be behind a firewall (that is, the resources
must not be accessible through any means besides the API proxy or another API that is well secured).
Think of grant types as different paths or interactions an app can take to gain an access token. Each grant type
addresses one or more use cases, and you'll need to select which grant type(s) to use based on your own needs.
In general, each grant type has advantages and disadvantages, and you'll need to weigh the tradeoffs based on
your business use cases. One important consideration is the "trustworthiness" of the apps that will be accessing
your data. Generally, third-party apps are less trustworthy than apps that are developed and used within an
enterprise.
SAP API Management supports the four main OAuth 2.0 grant types:
• authorization code -- Considered the most secure grant type. Before the authorization server issues an
access token, the app must first receive an authorization code from the resource server. You've seen this flow
anytime your app opens a browser to the resource server's login page and invites you log in to your actual
account (for example, Facebook or Twitter).
If you successfully log in, the app will receive an authorization code that it can use to negotiate an access
token with the authorization server. Typically, this grant type is used when the app resides on a server rather
than on the client. This grant type is considered highly secure because the client app never handles or sees
the user's username or password for the resource server (that is, for example, the app never sees or handles
your Twitter credentials). This grant type flow is also called "three-legged" OAuth.
• implicit -- Considered a simplified version of authorization code. Typically this grant type is used when the
app resides on the client. For example, the app's code is implemented in a browser using JavaScript or
another scripting language (instead of residing and running on a separate web server). In this grant type flow,
the authorization server returns an access token directly when the user is authenticated, rather than issuing
an authorization code first. Implicit grants can improve app responsiveness in some cases, but this advantage
needs to be weighed against possible security implications as described in the IETF specification.
• resource owner password credentials -- In this flow, the client is issued an access token when the user's
username/password are validated by the authorization server. This flow is recommended for highly trusted
applications. An advantage of this flow over, say, basic authentication, is that the user only presents his
username/password once. From then on, the access token is used.
An access token is a long string of characters that serves as a credential used to access protected resources.
Resources tokens (also called bearer tokens) are passed in Authorization headers, like this:
The resource server understands that the access token "stands in" for credentials like username and password. In
addition, the access tokens can be issued with restrictions, so that, for example, the app can read but not write or
delete data on the resource server. Note that an access token can be revoked if, for instance, the app is
compromised. In this case, you will need to get a new access token to continue using the app; however, you will
not have to change your username or password on the protected resources server (for example, Facebook or
Twitter).
Access tokens generally have an expiration (for security reasons). Some grant types allow the authorization
server to issue an refresh token, which allows the app to fetch a new access token when the old one expires. For
more details on access and refresh tokens, refer to the IETF OAuth 2.0 specification.
Through the mechanism of scopes, OAuth 2.0 can grant an app limited access to protected resources. For
example, an app may have access only to specific resources, may be able to update resources, or may only be
granted read-only access. Under so-called "three-legged" OAuth flows, the user typically specifies the level of
access through a consent page (for example, a web page where the user selects the scope with a checkbox of
other mechanism).
All clients (apps) must register with the OAuth 2.0 authorization server from which they intend to request access
tokens. When you register an app, you receive back a set of keys. One is a public key called the client identifier,
and the other is a secret key called the client secret. Without these keys, an app cannot issue requests for
authorization codes or access tokens to the authorization server. Note that while the IETF OAuth specification
calls these keys client ID and client secret, the SAP API Management UI calls them the Consumer ID and
Consumer secret. They are equivalent.
Which OAuth 2.0 grant type flow you chose to implement depends on your specific use case, as some grant types
are more secure than others. Your choice of grant types depends on the trustworthiness of the client app and
requires very careful consideration, as described in the following table:
B2B Highly trusted apps, written by internal developer Client credentials Typically, the app
(extranet), or developers with a trusted business relationship is also the resource
intranet, with the API provider. owner
other Apps that need to access resources on their own Requires Client ID
behalf. and Client secret
keys
Requires app to be
registered with
service provider
Intranet Trusted apps written by internal or trusted third- Password Requires client Id
sites, party developers. Implicit and secret, plus
portals A good example is logging in to your company HR username and
site to make insurance selections, submit reviews, password
or change personal information. Requires app to be
registered with
service provider
B2C There is an individual end user (mobile user) Implicit Requires app to be
involved, and user credentials are stored on the registered with the
mobile device. service provider.
User credentials
are stored on the
device running the
app.
It is relatively simple to 'step up' your API security scheme from API key validation to OAuth client credentials.
Both schemes use the same consumer key and secret to validate the client app. The difference is that client
credentials provides an extra layer of control, since you can easily revoke an access token when needed, without
requiring you to revoke the app's consumer key. To work with the default OAuth endpoints, you can use any
consumer key and secret generated for app in your organization to retrieve access tokens from the token
endpoint. (You can even enable client credentials for apps that already have consumer keys and secrets.) For
details on API key validation, see API keys
With the client credentials grant type, an app sends it's own credentials (the Client ID and Client Secret) to a
GenerateAccessToken endpoint on SAP API Management. If the credentials are valid, it returns an access token
to the client app.
This topic offers a general description of the OAuth 2.0 client credentials grant type and discusses how to
implement this flow on SAP API Management.
Most typically, this grant type is used when the app is also the resource owner. For example, an app may need to
access a backend cloud-based storage service to store and retrieve data that it uses to perform its work, rather
than data specifically owned by the end user. This grant type flow occurs strictly between a client app and the
authorization server. An end user does not participate in this grant type flow.
Roles
Roles specify the "actors" that participate in the OAuth flow. Let's do a quick overview of the client credentials
roles to help illustrate where SAP API Management fits in. For a complete discussion of OAuth 2.0 roles, see
the IETF OAuth 2.0 specification.
• Client App -- The app that needs access to the user's protected resources. Typically, with this flow, the app
runs on server rather than locally on the user's laptop or device.
• SAP API Management -- In this flow, SAP API Management is the OAuth authorization server. It's role is to
generate access tokens, validate access tokens, and pass authorized requests for protected resources on to
the resource server.
• Resource Server -- The backend service that stores the protected data that the client app needs permission
to access. If you are protecting API proxies hosted on SAP API Management, then SAP API Management is
also the resource server.
Here is a summary of the steps required to implement the client credentials code grant type where SAP API
Management serves as the authorization server. Remember, with this flow, the client app simply presents its
client ID and client secret, and if they are valid, SAP API Management returns an access token.
Prerequisite: The client app must be registered with SAP API Management to obtain the client ID and client secret
keys. See Registering client apps for details.
Note
Although you can pass the client_id and client_secret values as query parameters as shown above, it's a
good practice to pass them as a base64 URL encoded string in the Authorization header. To do this, you
need to use a base64 encoding tool or utility to encode the two values together with colon separating
them. Like this: aBase64EncodeFunction(clientidvalue:clientsecret). So, the example above would be
encoded like this:
result = aBase64EncodeFunction(ns4fQc14Zg4hKFCNaSzArVuwszX95X:ZIjFyTsNgQNyxI) // Note the colon
separating the two values.
The result of base64 encoding the above string is:
bnM0ZlFjMTRaZzRoS0ZDTmFTekFyVnV3c3pYOTVYOlpJakZ5VHNOZ1FOeXhJOg==
Then, make the token request like this:
As the authorization server, SAP API Management processes requests for access tokens. As the API developer,
you need to create a proxy with a custom flow to handle token requests and add and configure an OAuthV2 policy.
This section explains how to configure that endpoint.
<OAuthV2 name="GetAccessToken">
<Operation>GenerateAccessToken</Operation>
<ExpiresIn>3600000</ExpiresIn>
<SupportedGrantTypes>
<GrantType>client_credentials</GrantType>
The API call to obtain the access token is a POST and includes an Authorization header with the base64 encoded
client_id + client+secret and the query parameter grant_type=client_credentials. It can also include optional
parameters for scope and state. For example:
To protect your API with OAuth 2.0 security, you need to add an OAuthV2 policy with the VerifyAccessToken
operation. This policy checks that incoming requests have a valid access token. If the token is valid, SAP API
Management processes the request. If it is not valid, SAP API Management returns an error.
To call an API that is protected with OAuth 2.0 security, you need to present a valid access token. The correct
pattern is to