0% found this document useful (0 votes)
659 views926 pages

SAP API Management User Guide

Uploaded by

Sam Moto30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
659 views926 pages

SAP API Management User Guide

Uploaded by

Sam Moto30
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 926

User Guide CUSTOMER

SAP API Management, On-Premise Edition


Typographic Conventions

Type Style Description

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 Emphasized words or expressions.

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.

EXAMPLE Keys on the keyboard, for example, F 2 or E N T E R .

CUSTOMER SAP API Management, On-Premise Edition


2 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Typographic Conventions
Document History

Version Date Change

1.0 2014-08-14 Document Created

1.1 2015-01-09 Added Java Callout Policy and Node.js

1.2 2016-05-01 Updated documentation with respect to SP04 Release

1.3 2016-06-22 Updated documentation with respect to SP05 Release

1.4 2016-10-15 Updated documentation with respect to SP06 Release

1.5 2017-05-04 Updated documentation with respect to SP07 Release

1.6 2017-11-21 Updated documentation with respect to SP08 Release

SAP API Management, On-Premise Edition CUSTOMER


Document History 3
Table of Contents

Data Protection and Privacy .............................................................................................................. 11

1 Overview - SAP API Management.......................................................................................... 12


1.1 What is an API? .....................................................................................................................................12
1.2 What is SAP API Management.............................................................................................................12
1.3 Making services available through SAP API Management Edge ......................................................13
1.4 Creating an API product in SAP API Management Edge...................................................................14
Allowing a client-side app to access your API product .....................................................15
Steps to create API products and making them available to developers .......................15
1.5 Components of SAP API Management...............................................................................................15
API Platform .........................................................................................................................16
Analytics Services ................................................................................................................16
Developer Services .............................................................................................................. 17
1.6 Making APIs available through SAP API Platform .............................................................................18
1.7 Developing with SAP API Platform......................................................................................................19
1.8 Organizations ........................................................................................................................................19
1.9 Environments ....................................................................................................................................... 23

2 Using the Management UI .................................................................................................... 24


2.1 Create a User as an Organization Administrator .............................................................................. 24
2.2 Using the SAP API Management Platform ........................................................................................ 25
Understanding the Base Path ............................................................................................ 26
Passing Credentials ............................................................................................................ 26
Running CURL Commands ................................................................................................ 26
2.3 Deployment Environments ................................................................................................................. 28
2.4 Testing .................................................................................................................................................. 28

3 Building APIs ......................................................................................................................... 29


3.1 What is an API Proxy ........................................................................................................................... 29
3.2 How is an API proxy represented? ..................................................................................................... 30
3.3 What is a policy? .................................................................................................................................. 30
3.4 Understanding flows ........................................................................................................................... 30
3.5 Understanding routes ......................................................................................................................... 32
3.6 Understanding the handling of request and response data ............................................................ 34
3.7 API development lifecycle................................................................................................................... 37
Environments ...................................................................................................................... 37
Deploying API proxies to environments ............................................................................ 38
Iterative development in test ............................................................................................. 39
Promotion to prod............................................................................................................... 39
3.8 Basic terminology ................................................................................................................................ 40
3.9 Best practices for API proxy design and development .....................................................................41
Development standards ..................................................................................................... 42
API proxy development ...................................................................................................... 42
Message payload size ......................................................................................................... 43

CUSTOMER SAP API Management, On-Premise Edition


4 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Table of Contents
Fault Handling ......................................................................................................................43
Persistence ..........................................................................................................................44
Policy and custom code ......................................................................................................44
Script Callouts (Java, JavaScript, Python) .......................................................................45
Accessing entities................................................................................................................46
Monitoring ............................................................................................................................46
Security ................................................................................................................................46
ServiceCallouts....................................................................................................................46
3.10 Implementing API Proxies ................................................................................................................... 47
Building a Simple API Proxy ............................................................................................... 47
Flows Configuration ............................................................................................................ 53
Flow Variables and Conditions ........................................................................................... 57
Mapping Conditional Flows to API Resources ..................................................................62
Introduction to Flow Variables ...........................................................................................68
Reusable Shared Flows ....................................................................................................... 77
Policy Attachment and Enforcement ................................................................................ 81
Rate-Limiting ...................................................................................................................... 90
Persistence .......................................................................................................................... 91
HTTP Response Caching ....................................................................................................93
Fault Handling ......................................................................................................................99
Pattern matching in conditional statements ...................................................................113
Resource Files.................................................................................................................... 122
JMS Integration ................................................................................................................. 127
Adding CORS Support to an API proxy ............................................................................131
Exposing a SOAP Service as an API Proxy ...................................................................... 136
Streaming Requests and Responses............................................................................... 142
3.11 Deploying API Proxies ....................................................................................................................... 143
Deploying API proxies to Environments .......................................................................... 143
Understanding Deployment ............................................................................................. 145
Deploying Proxies in the UI ............................................................................................... 147
Deploy API proxies using the Management API .............................................................. 151
3.12 Building Proxies with Node.js............................................................................................................ 159
Getting started with Node.js............................................................................................. 160
Deploying a Standalone Node.js app ............................................................................... 162
Understanding Support for Node.js Modules .................................................................. 171
Understanding support for the http and https modules ................................................ 173
Understanding support for the tls module ...................................................................... 174
Why the cluster module is disabled ................................................................................. 174
Advanced ScriptTarget Configuration............................................................................. 175
Using the SAP API Management-access module ........................................................... 175
Debugging Node.js proxies............................................................................................... 185
Understanding Support for Node.js Modules ................................................................. 187
3.13 Debug and Troubleshoot....................................................................................................................191
Using a Trace Tool ..............................................................................................................191
How to use Trace ................................................................................................................191
How to read a Trace .......................................................................................................... 192
Transaction map legend ................................................................................................... 193
Understanding the phase details ..................................................................................... 194
Debugging with Trace ....................................................................................................... 195
Selecting View Options ..................................................................................................... 195

SAP API Management, On-Premise Edition CUSTOMER


Table of Contents 5
Downloading trace results................................................................................................ 196
Using Offline Trace Tool ................................................................................................... 197
Troubleshooting ................................................................................................................ 198
View API History ................................................................................................................ 201
3.14 Environment Configurations ............................................................................................................203
Creating and Editing an Environment Cache ..................................................................203
Creating and Editing an Environment Key/Value Maps ................................................205
About scope.......................................................................................................................206
Load Balancing Across Backend Servers ....................................................................... 207
Managing target servers with the UI ...............................................................................209
Managing target servers with APIs.................................................................................. 210
Configuring a TargetEndpoint to load balance across named TargetServers ............. 211
Configuring a target server for SSL ................................................................................. 215
Virtual Hosts ......................................................................................................................220

4 Secure APIs ......................................................................................................................... 226


4.1 Org Administration ............................................................................................................................ 226
What are organization users? .......................................................................................... 226
What SAP API Management entities do organization users work with? ...................... 226
Manage Users and Roles .................................................................................................. 226
Assign Roles ...................................................................................................................... 228
Creating custom roles in the UI ....................................................................................... 233
Creating roles with the API ............................................................................................... 235
4.2 OAuth .................................................................................................................................................. 239
OAuth 2.0 ........................................................................................................................... 239
OAuth v1.0a policy ............................................................................................................ 347
4.3 TLS/SSL ............................................................................................................................................. 351
SSL terminology ................................................................................................................ 351
Using SSL with SAP API Management ............................................................................ 359
Configuring TLS................................................................................................................. 363
Configuring SSL ................................................................................................................ 363
Configuring SSL to the Backend Service ........................................................................ 372
KeyStores and TrustStores.............................................................................................. 376
Using SSL On Developer Portal ....................................................................................... 385
4.4 API Keys..............................................................................................................................................388
Policy Configuration..........................................................................................................388
Policy Attachment.............................................................................................................389
Submitting a Request with a valid API Key .................................................................... 390
4.5 SAML.................................................................................................................................................. 390
4.6 Last-Mile Security .............................................................................................................................. 391
Client SSL........................................................................................................................... 391
Outbound Authentication ................................................................................................. 391
API key................................................................................................................................ 392
OAuth Client Credentials .................................................................................................. 392
4.7 Content-Based Security.................................................................................................................... 392
JSON threat protection .................................................................................................... 393
XML threat protection ...................................................................................................... 393
General content protection .............................................................................................. 393
4.8 Data Masking ..................................................................................................................................... 393
Overview ............................................................................................................................ 393

CUSTOMER SAP API Management, On-Premise Edition


6 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Table of Contents
Using Mask Configurations.............................................................................................. 394
Configuring a mask configuration resource................................................................... 395
Mask Configuration API ................................................................................................... 396

5 Publishing APIs ................................................................................................................... 399


5.1 Publishing Overview.......................................................................................................................... 399
Task 1: Create an API product ......................................................................................... 400
Task 2: Register an App Developer ................................................................................. 400
Task 3: Register an App .................................................................................................... 401
Task 4: Document your APIs ........................................................................................... 402
SmartDocs ........................................................................................................................ 403
How to document your APIs by using SmartDocs ........................................................ 404
Configuring the SmartDocs module ............................................................................... 405
What is an API product?................................................................................................... 406
Creating API Products ..................................................................................................... 407
Adding Developers to your Organization ........................................................................ 412
Registering Apps ............................................................................................................... 415
Using the Management API to Publish APIs ................................................................... 419

6 Analyzing APIs..................................................................................................................... 428


6.1 Analytics Services Overview ............................................................................................................ 428
Improve your API through Analytics............................................................................... 428
Insight that leads to action .............................................................................................. 428
What kind of data is collected and analyzed? ................................................................ 429
A new breed of data.......................................................................................................... 430
Put Analytics up front (a best practice) .......................................................................... 431
Your API at a glance .......................................................................................................... 431
Fetch analytics data with the REST API ......................................................................... 433
Share data with app developers...................................................................................... 433
6.2 Dashboard Homepage...................................................................................................................... 436
SAP API Management Dashboard .................................................................................. 436
API Dashboards ................................................................................................................ 436
Developer Dashboard ...................................................................................................... 438
Exploration Dashboards .................................................................................................. 440
6.3 Analytics Dashboard.......................................................................................................................... 441
Using the analytics dashboards ....................................................................................... 441
SAP API Management Dashboard .................................................................................. 445
Create Custom Reports ................................................................................................... 468
Use the analytics API to measure API program performance ......................................472
Analyze API message content using custom analytics................................................. 483
Use Custom Aggregations ............................................................................................... 492
Troubleshooting with Analytics....................................................................................... 495

7 References........................................................................................................................... 498
7.1 Analytics Command Reference ....................................................................................................... 498
API...................................................................................................................................... 498
Developers ........................................................................................................................ 500
Apps................................................................................................................................... 502
API Products ..................................................................................................................... 504
API Resources................................................................................................................... 506

SAP API Management, On-Premise Edition CUSTOMER


Table of Contents 7
API program-wide analytics .............................................................................................508
7.2 Analytics Dimensions and Metrics ................................................................................................... 510
Dedicated dimensions ...................................................................................................... 510
Computed metrics ............................................................................................................. 511
Metrics ............................................................................................................................... 512
Functions ........................................................................................................................... 514
Dynamic Dimensions ........................................................................................................ 514
Virtual dimensions .............................................................................................................517
Report Filters ..................................................................................................................... 518
7.3 API Proxy Configuration Reference ................................................................................................. 519
API proxy structure ........................................................................................................... 519
Configuration files and directory structure of an API proxy..........................................520
Base Configuration ...........................................................................................................520
ProxyEndpoint ................................................................................................................... 522
ProxyEndpoint Configuration Elements.......................................................................... 523
How to Configure RouteRules .......................................................................................... 525
Conditional Routes............................................................................................................ 525
Null Routes......................................................................................................................... 526
TargetEndpoint ................................................................................................................. 526
TargetEndpoint Configuration ......................................................................................... 527
TargetEndpoint Configuration Elements ........................................................................ 527
TLS/SSL TargetEndpoint Configuration ........................................................................ 529
Using flow variables to set TLS/SSL values dynamically..............................................530
Using references to set TLS/SSL values dynamically ................................................... 531
TargetEndpoint with target load balancing .................................................................... 532
Policies ............................................................................................................................... 532
Policy Attachment............................................................................................................. 533
Flows .................................................................................................................................. 534
Conditional Flows .............................................................................................................. 535
Flow Configuration Elements ........................................................................................... 536
Step processing................................................................................................................. 536
Resources .......................................................................................................................... 537
7.4 Conditions reference ......................................................................................................................... 537
Path Expressions............................................................................................................... 539
Operators ...........................................................................................................................540
Relational operators and null operands .......................................................................... 541
Operands ........................................................................................................................... 541
Literals................................................................................................................................ 542
7.5 Endpoint properties reference ......................................................................................................... 543
TargetEndpoint Transport Properties............................................................................. 543
TargetEndpoint Transport Property Specification ........................................................ 544
ProxyEndpoint Transport Properties .............................................................................. 546
ProxyEndpoint Transport Property Specification.......................................................... 547
7.6 JavaScript Object Model ................................................................................................................... 548
Background ....................................................................................................................... 549
Overview ............................................................................................................................ 549
Context...............................................................................................................................550
The request and response objects ..................................................................................550
The print() function...........................................................................................................550
crypto object reference .................................................................................................... 551

CUSTOMER SAP API Management, On-Premise Edition


8 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Table of Contents
Context methods .............................................................................................................. 556
Context Properties ........................................................................................................... 556
Messages ........................................................................................................................... 557
7.7 OAuth Error Code Reference ........................................................................................................... 563
Authorization Code .......................................................................................................... 563
Generate AccessToken .................................................................................................... 564
Implicit ............................................................................................................................... 565
Refresh Token................................................................................................................... 566
Verify AccessToken.......................................................................................................... 566
7.8 OAuth Flow Variables ........................................................................................................................567
OAuth 2.0 Flow Variables .................................................................................................567
OAuth 1.0a Flow Variables ................................................................................................574
7.9 Variables Reference...........................................................................................................................576
About variable scope.........................................................................................................576
Request message variables..............................................................................................576
Response Message Variables...........................................................................................585
Message variables ............................................................................................................ 589
Path Variables .................................................................................................................... 591
Configuration Variables ................................................................................................... 593
System Variables.............................................................................................................. 593
SSL/TLS Variables ........................................................................................................... 595
Policy Variables .................................................................................................................597

8 Policy Reference ................................................................................................................. 598


8.1 Policy Reference Overview............................................................................................................... 598
8.2 Traffic Management Policies ........................................................................................................... 598
Optimize Performance Using Cache .............................................................................. 599
Rate Limit API Traffic Using Quota ................................................................................. 629
Reduce latency using ResponseCache ...........................................................................637
8.3 Element reference............................................................................................................................. 639
8.4 <ResponseCache> attributes.......................................................................................................... 640
Shield APIs Using SpikeArrest ......................................................................................... 651
Reset Quota Counter Using ResetQuota........................................................................ 659
Throttle Backend Connections Using ConcurrentRatelimit .......................................... 661
8.5 Security Policies ................................................................................................................................ 663
Authorize Requests Using OAuth 1.0a ........................................................................... 663
Authorize Requests Using OAuth 2.0 .............................................................................. 671
Authorize Requests using OAuthV2 Policy .................................................................... 685
Retrieve Token Attributes Using GetOAuthV2Info......................................................... 716
Set OAuth Token Attributes Using SetOAuthV2Info......................................................723
Delete Authorization Code or Access Token using DeleteOAuthV2Info ......................728
OAuth HTTP Status Codes ............................................................................................... 731
Authenticate and Authorize Using SAML 2.0 ................................................................. 737
Authenticate to Backend Services Using Basic Authentication....................................743
Manage Client Access Using IP-based Access Control ................................................. 751
Minimize API Vunerabilities Using JSON Threat Protection .........................................762
Minimize API Vulnerabilities Using XML Threat Protection ..........................................764
Search Threat Patterns Using Regular Expression ........................................................770
Verify API Keys Using API Key Validation........................................................................ 775
Authenticating Users and Getting User Distinguished Names in LDAP Policy............ 779

SAP API Management, On-Premise Edition CUSTOMER


Table of Contents 9
8.6 Extension Policy ................................................................................................................................. 785
Call services or APIs using ServiceCallout...................................................................... 785
Capture Analytics from API Traffic.................................................................................. 788
Customize an API Using JavaScript ................................................................................790
Customize an API Using Python ...................................................................................... 796
Message Logging Policy ................................................................................................... 798
8.7 Mediation Policies............................................................................................................................. 806
ExtractVariables Policy.................................................................................................... 806
Apply XSL Transformations .............................................................................................820
Exception Handling With RaiseFault................................................................................ 823
Generate or Modify Messages Using AssignMessage ...................................................826
Persist Data Using KeyValueMap ....................................................................................850
Retrieve Entity Profiles Using AccessEntity ...................................................................862
Validate XML and SOAP Using MessageValidation ....................................................... 871
JSON Threat Protection policy error codes.................................................................... 877
XML Threat Protection policy error codes..................................................................... 880
Convert XML to JSON .......................................................................................................882
JSON payloads in Assign Message and Raise Fault.......................................................896
Convert JSON to XML .......................................................................................................896
8.8 Target Servers ................................................................................................................................... 901
Create a TargetServer ...................................................................................................... 901
Delete a TargetServer ...................................................................................................... 906
List TargetServers in an environment ............................................................................ 906
Get a TargetServer............................................................................................................907
Update a TargetServer .....................................................................................................907
8.9 Java Callout Policy ............................................................................................................................. 910
Samples ............................................................................................................................. 910
Element reference ............................................................................................................. 910
<JavaCallout> attributes.................................................................................................. 910
<DisplayName> element ................................................................................................... 911
<ResourceURL> element .................................................................................................. 911
<ClassName> element ..................................................................................................... 912
Error reference .................................................................................................................. 912
Referencing the Java class in a JavaCallout policy ........................................................ 914
Coding the Java class ....................................................................................................... 914
Error handling .................................................................................................................... 915
Specifying the default target endpoint............................................................................ 916
Testing the example.......................................................................................................... 916
Usage notes ....................................................................................................................... 918
8.10 Flow Callout Policy............................................................................................................................. 918
About the Flow Callout Policy .......................................................................................... 919
Element reference ............................................................................................................. 919
<FlowCallout> attributes.................................................................................................. 919
<DisplayName> element ..................................................................................................920
<SharedFlowBundle> element ........................................................................................920
Flow Variables ................................................................................................................... 921
Error Codes........................................................................................................................ 921

9 Glossary ............................................................................................................................... 922

CUSTOMER SAP API Management, On-Premise Edition


10 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Table of Contents
Data Protection and Privacy

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.

SAP API Management, On-Premise Edition CUSTOMER


Data Protection and Privacy © 2014 SAP SE or an SAP affiliate company. All rights reserved. 11
1 Overview - SAP API Management

1.1 What is an API?

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.

1.2 What is 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:

CUSTOMER SAP API Management, On-Premise Edition


12 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
Because providers make their services available over the web, they must ensure that they have taken all
necessary steps to secure and protect their services from unauthorized access. As a service provider, consider:
• Security - How will you control access to your services to prevent unauthorized access?
• Compatibility - Will your services work across different platforms and devices?
• Measurability - How can you monitor your services to make sure they are available?
• And many other considerations
After a client app has been released that accesses any services, the service provider is then required to make sure
that those services continue to work overtime as they add, modify, or delete those services. The service provider
must also have a way to keep app developers aware of any changes to the services to ensure that client apps stay
in sync with those services.
Client app developers face challenges when trying to consume services from different providers. There are many
technologies available today for use by a service provider to expose its services. The same client app might have
to use one mechanism to consume a service from one provider, and a different mechanism to consume a service
from a different provider. App developers can even face the situation where they have to use different
mechanisms to consume services from the same provider.

1.3 Making services available through SAP API Management


Edge

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.

SAP API Management, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 13
Enables you to take advantage of the analytics, monetization, developer portal, and other features built into SAP
API Management Edge.
The following image shows an architecture with SAP API Management Edge 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 Edge. 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 Edge handle the security and authorization tasks
required to protect your services, as well as to analyze, monitor, and monetize 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,
add security, execute conditional logic or custom code, and to perform many other actions. The important thing
to remember is you implement policies on SAP API Management Edge, not on your backend server.

1.4 Creating an API product in SAP API Management Edge

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.

CUSTOMER SAP API Management, On-Premise Edition


14 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
Allowing a client-side app to access your API product

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.

Steps to create API products and making them


available to developers

• 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.

1.5 Components of SAP API Management

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, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 15
API Platform

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.

CUSTOMER SAP API Management, On-Premise Edition


16 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
The Management UI lets you perform most analytics management tasks in a browser, as shown in the following
figure:

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, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 17
1.6 Making APIs available through SAP API Platform

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,

CUSTOMER SAP API Management, On-Premise Edition


18 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
add security, execute conditional logic or custom code, and to perform many other actions. The important thing
to remember is you implement policies on SAP API Management, not on your backend server.

1.7 Developing with SAP API Platform

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:

SAP API Management, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 19
Example
An organization can contain one or more users and one or more API products, while an app uses a single
key to access one or more API products.

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

Organization Every SAP API Management account maps to one or more


organizations on SAP API Management. The organization
contains a representation of all components including API
proxies, API products, API packages, apps, and developers.
Account holders are not limited to a single organization. Some
account holders might define or be a member of multiple
organizations that support different app developer
communities.

User Within an organization, where the person creating the account


is automatically an administrator, you can create more users.
Users make up the organization's API team, which can include
people such as administrators, API proxy and API product
creators, users monitoring analytics and other statistics, and
any others.
Different users can have different roles and access privileges.
For example, define some users as Organization Administrators
and Operations Administrators with privileges to modify the
organization and its components. Define other users with

CUSTOMER SAP API Management, On-Premise Edition


20 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
Component Description
permissions to create API proxies and API products, but without
the privileges to modify other users.
Users can be members of multiple organizations. For example,
your company might define multiple organizations on SAP API
Management to support different developer communities.
Internally though, the same people build all of the API proxies
and API products and are therefore members of all of your
organizations.
You do not have to create an SAP API Management account—
that is, create an SAP API Management organization—to be a
user. An administrator can add you to an existing organization.

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.

Developer An organization contains one or more developers who build the


apps that consume the APIs (assembled into API products)
defined by your organization. Developers consume APIs but
cannot create APIs or perform any other actions in the
organization.
Developers can be internal to your company, they can be
partners, or they can be external developers who pay for access
to your APIs.
Developers must be registered in your organization before they
can register an app and receive an API key to access your APIs.
As an API provider, it is up to you to determine how to add,
update, or remove developers in your organization. You can
manually add them through the SAP API Platform management
UI, create a developer portal to register them through a website,
or define your own registration mechanism by using the SAP
API Platform management API.

SAP API Management, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 21
Component Description
A developer is not required to have an account on SAP API
Platform, and most developers will not need to know anything
about SAP API Platform. If the developer does have an account
on SAP API Platform, it is typically as a user in a different
organization, or to use the API Platform.
Because your API developers are registered in your
organization, you can use SAP API Platform to monitor and
collect analytic information on developers and their use of your
APIs.

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.

CUSTOMER SAP API Management, On-Premise Edition


22 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Overview - SAP API Management
1.9 Environments

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.

SAP API Management, On-Premise Edition CUSTOMER


Overview - SAP API Management © 2014 SAP SE or an SAP affiliate company. All rights reserved. 23
2 Using the Management UI

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

2.1 Create a User as an Organization Administrator

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.

CUSTOMER SAP API Management, On-Premise Edition


24 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Using the Management UI
To add a new user account:
1. Log in to SAP API Management Platform with an account that has administration privileges for the
organization.
If you are a member of multiple organizations, select the correct organization from the list in the upper right of
the SAP API Management UI.
2. Choose the Admin tab.
3. Choose + User. The "New User" screen appears.
4. Enter the user's Email address, First Name, and Last Name.
5. Select the user's Role. See Manage users and roles for more information. Set the Role as either:
o User
o Business User
o Organization Administrator
o Operations Administrator
6. Choose Save.
The new user will receive an email with further instructions.

To add an existing user to your organization


Use this same procedure to add an existing user to your organization. The only difference is that in step 4, if you
enter the email address of an existing user, the First Name and Last Name fields are automatically filled.

To delete a user from your organization


To delete a user from your organization, select the user in the Organization Users table and choose Delete. This
only removes the user from the current account. If the user is a member of multiple accounts, they remain in the
system.

2.2 Using the SAP API Management Platform

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.

SAP API Management, On-Premise Edition CUSTOMER


Using the Management UI © 2014 SAP SE or an SAP affiliate company. All rights reserved. 25
o POST: Creates a resource, or passed in a parameter, performed an action on resource. For example,
when you revoke OAuth access tokens, you use the POST method along with the parameter
action=revoke.
o PUT: Updates an existing resource.
o DELETE: Deletes an existing resource.

Understanding the Base Path

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==

Running CURL Commands

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.

CUSTOMER SAP API Management, On-Premise Edition


26 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Using the Management UI
Note
On Windows, make sure to download a version of cURL that includes the libcurl library. Also on Windows,
you might need to use a flag to disable the trust check that cURL performs against the SSL certificate
presented by the SAP API Management. You can do this by adding -k to each request you submit via
cURL on the command line. This only disables the trust check and does not disable encryption.

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.

Example: making an API call to SAP API Management


In this example, you make an API call to SAP API Platform. The API call in this example returns a list of the names
of all API proxies in your organization. Copy and paste the following command into the terminal window on your
computer.
$ curl http://<host:port>/v1/organizations/{org_name}/apis -u myname:mypass
For brevity, you can abbreviate /organizations as /o. For example, if your username is [email protected],
your password is secret, and your account in the organization called apifactory, then the request looks like this:
$ curl http://<host:port>/v1/o/apifactory/apis -u [email protected]:secret
The response should contain a JSON array with the API proxies which are created:
[ "oauth", "weatherapi" ]
cURL has a few tools that can make you life easier. For example, you often need to see the HTTP headers
associated with a request. To obtain this detail about an HTTP request, you can use the -v flag provided by curl.
For example:
$ curl http://<host:port>/v1/o/{org_name}/apis -u myname:mypass -v
If you only want to see the HTTP headers on the response from the SAP API Management (and not the content),
then you can use the -I flag.
$ curl http://<host:port>/v1/o/{org_name}/apis -u myname:mypass -I

Example: returning XML


JSON is the default format for response messages. If you require XML, you can add an HTTP Accept header to get
an XML response instead of JSON:
$ curl -H "Accept:text/xml" http://<host:port>/v1/organizations/apifactory/apis -u
[email protected]:secret
When POSTing or PUTting payloads in XML, use the Content-type HTTP header:
$ curl -H "Content-type:text/xml" -X POST -d \

SAP API Management, On-Premise Edition CUSTOMER


Using the Management UI © 2014 SAP SE or an SAP affiliate company. All rights reserved. 27
'<XMLPayload>
</XMLPayload> ' \
http://<host:port>/v1/organizations/apifactory/apis \
-u [email protected]:secret

2.3 Deployment Environments

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.

CUSTOMER SAP API Management, On-Premise Edition


28 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Using the Management UI
3 Building APIs

3.1 What is an API Proxy

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 29
3.2 How is an API proxy represented?

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.

3.3 What is a policy?

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.

3.4 Understanding flows

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.

What are flows?


API proxies define request and response flows that are executed in a specific order. The order allows you to apply
logic and behavior at specific points in the API proxy execution. The request and response flows are subdivided
into proxy and target segments. Each segment is subdivided into the following flow 'stages':
• PreFlow: Always executes before any conditional flows.
• Conditional flows: One or more flows, each of which has an associated condition. Conditional flows tell SAP
API Management, "When you see this, perform this logic." For example, when an API call is a GET on
the /movies resource (the condition), transform the response to JSON (through a policy attached to the
conditional flow). Only one flow executes per transaction—the first flow whose condition evaluates to true.
• PostFlow: Always executes after any conditional flows.
• PostClientFlow: An optional flow that executes after the response message has been sent to the requesting
client app. (This is a specialized flow, and only MessageLogging policies can be attached to it.)
The following figure shows a basic request and response exchange between an app and a backend service. In this
figure, the ProxyEndpoint and TargetEndpoint have been expanded to show the flows used to process the request
and response:

CUSTOMER SAP API Management, On-Premise Edition


30 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
This may look complicated, but it's fairly simple once you understand a few use cases. Flows are executed in the
following order in both the Proxy Endpoint and the Target endpoint, first in the request, then in the response.

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.

4. PostClientFlow (response only)


You can add an optional PostClientFlow to the ProxyEndpoint that executes after the request is returned to the
requesting client app. Only MessageLogging policies can be attached to this flow, which are executed after the
response is sent. This reduces API proxy latency and makes information available for logging that is not calculated

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 31
until after the response is sent, such as the client.send.start.time andclient.send.end.time. The flow is used
primarily for measuring the time interval between the start and end timestamps for the response message.

3.5 Understanding routes

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.

Determining the URL of the API proxy endpoint


The following image shows a request coming in to the ProxyEndpoint from an app, and that request being directed
to the backend service:

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

CUSTOMER SAP API Management, On-Premise Edition


32 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
If you examine the ProxyEndpoint definition for the API proxy in the figure above, you can see how this URL is
parsed by SAP API Management:
The domain portion of the URL, http://myOrg-prod.<host:port>, corresponds to a virtual host on SAP API
Management. In the ProxyEndpoint definition above, the API proxy uses the <VirtualHost> tag to reference a
virtual host named default. You can have multiple virtual hosts defined in your environment.

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.

Determining the URL of the target endpoint


The <RouteRule> tag in a ProxyEndpoint definition determines the target of the API proxy, and is evaluated after
all policies in the PreFlow, Conditional Flows, and PostFlow of the ProxyEndpoint are processed.
A ProxyEndpoint can define the target as:
• A direct URL to a backend service.
• A single TargetEndpoint definition.
• Multiple TargetEndpoints where the API proxy delegates the request to a target endpoint based on a
condition.
• Null route or target, meaning the request is not forwarded to a target. Instead, all of the processing of the
request, and the generation of the response, occurs on SAP API Management.

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 33
All requests to this API proxy are directed to the same TargetEndpoint definition. The <URL> tag in the
TargetEndpoint determines the location of the backend service. in the figure above, the target URL
is http://weather.yahooapis.com.

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

3.6 Understanding the handling of request and response


data

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

CUSTOMER SAP API Management, On-Premise Edition


34 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
By default, all data in a request is passed unchanged from the ProxyEndpoint to the TargetEndpoint. Therefore,
when the TargetEndpoint makes the request to the backend server, all information in the original request is
passed to the backend service.

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.

How request data passed to the backend server?


The following image shows an API proxy definition:

For this API proxy:


• API proxy virtual host: default
• Domain defined by the virtual host: http://myOrg-prod.<host:port>
• Proxy base path: /v1/weather
• TargetEndpoint specifid by route rule: default
• Target URL: http://weather.yahooapis.com

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}

The flow variables are set with the following values:


• request.verb: GET
• proxy.basepath: /v1/weather
• proxy.pathsuffix: forecastrss
• request.querystring: w=12797282

Note
There are many different flow variables created during the processing of a request and response.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 35
The TargetEndpoint then makes a request to the backend service using information from the request:

{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:

curl -X GET http://weather.yahooapis.com/forecastrss?w=12797282

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:

curl -X GET -H 'Content-type:application/xml' http://myOrgprod-


<host:port>/v1/weather/forecastrss?w=12797282

Or a request in the form below to include a header and form data:

curl -X POST -H "Content-type:application/json" -d \


'{"email" : "[email protected]",
"firstName" : "Jane",
"lastName" : "Tutorial",
"userName" : "jtutorialxml"
}' \
http://myOrg-prod.<host:port>/v1/register/user

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.

How is response data returned?


By default, all data received by SAP API Management from the backend service in the response is passed
unchanged to the app that originated the request. As described above for the request, the data returned in the
response is accessible through flow variables on SAP API Management.

Manipulating request and response data in an API proxy


There are many times where you want to modify request data before sending it to he backend server. For
example:
• To remove security information used by SAP API Management to validate requests. That information is not
required by the backend service.
• To add data sent to the backend service, for example to track users or to gather analytics.

CUSTOMER SAP API Management, On-Premise Edition


36 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• To conditionally process the request based on request data. For example, an API proxy can have multiple
TargetEndpoints. The TargetEndpoint used by the request is determined by request data. You then strip that
data from the request before sending it to the backend service.

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.

3.7 API development lifecycle

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 37
Inbound, server SSL is automatically enabled for each environment. Two VirtualHosts are pre-defined in each
environment: default and secure. 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 defaultVirtualHost from the
API proxy configuration.
For example, the following ProxyEndpoint listens on HTTP and HTTPS.

<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.

Deploying API proxies to environments

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.

CUSTOMER SAP API Management, On-Premise Edition


38 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Iterative development in test

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 39
3.8 Basic terminology

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

CUSTOMER SAP API Management, On-Premise Edition


40 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Term Definition
making requests. API Services implements security around the API key through direct API key
validation or through OAuth.

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.

version The version of the developer-facing API interface.


For example, pivotaltracker.com/services/v3, or <host:port>/v1.
This term is distinguished from 'revision', which is the numbered, version-controlled package
of configuration and policies bundled into an API Proxy. API interfaces have versions; API
proxies have revisions.

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.

3.9 Best practices for API proxy design and development

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 41
Development standards

Comments and Documentation


• Provide inline comments in the ProxyEndpoint and TargetEndpoint configurations. Comments enhance
readability for a Flow, especially where policy file names are not sufficiently descriptive to express the
underlying functionality of the Flow.
• Make comments useful. Avoid obvious comments.
• Use consistent indentation, spacing, vertical alignment, etc.

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.

API proxy development

Initial Design Considerations


Leverage SAP API Management policies and functionality wherever possible to build API proxies. Avoid coding all
proxy logic in JavaScript, Java, or Python resources.

CUSTOMER SAP API Management, On-Premise Edition


42 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Do not call the SAP API Management API from inside API proxies. The SAP API Management API is used for
administrative management purposes, not API flow logic. Policies are provided for interaction with API Services
entities, such as developers, apps, access tokens and so on.

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.

Message payload size

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 43
Persistence

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.

Policy and custom code

Policy or custom code?


• Use built-in policies first and foremost (when possible). SAP API Management policies are hardened,
optimized, and supported. For example, use the standard AssignMessage and ExtractVariables policies
instead of JavaScript (when possible) to create payloads, extract information from payloads (XPath,
JSONPath), etc.
• JavaScript is preferred over Python and Java. However, if performance is the primary requirement, Java
should be used over JavaScript.

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.

CUSTOMER SAP API Management, On-Premise Edition


44 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• Always use JavaScript Steps and put files in jsc resources folder. JavaScript Policy type pre-complies the
code at deployment time.

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.

Script Callouts (Java, JavaScript, Python)

• Use a global try/catch, or equivalent.


• Throw meaningful exceptions and catch these properly for use in fault responses.
• Throw and catch exceptions early. Do not use the global try/catch to handle all exceptions.
• Perform null and undefined checks, when necessary. An example of when to do this is when retrieving
optional flow variables.
• Avoid making HTTP/S requests inside of a script callout. Instead, use the SAP API Management
ServiceCallout policy as the policy handles connections gracefully.

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 45
Accessing entities

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.

SAP API Management Analytics


Analytics can provide non-critical API monitoring as error percentages are measured.

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.

CUSTOMER SAP API Management, On-Premise Edition


46 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
3.10 Implementing API Proxies

Building a Simple API Proxy

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.

Creating an API Proxy in the SAP API Management UI

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 47
Creating an API Proxy for an HTTP Service

API Platform generates API proxies based on two pieces of information:


o The URL of the backend service
o The URI path that uniquely identifies the API that will be exposed by the API proxy to consumer apps
The backend service URL typically represents a service-enabled application owned by your organization. It can
also point to a publicly available API. The API or service can be under your control "(for example, any SAP
Gateway Odata service, Enterprise SOAP Service) or it can be a third-party API or service.
To add an API proxy for an existing HTTP service:
1. Under Choose Your Starting Point:
o Select Existing Backend service.
o Enter the Backend Service URL, for example, http://weather.yahooapis.com. The Backend Service
URL defines the target URL that SAP API Management invokes on behalf of apps. You can add any URL
that is accessible to the SAP API Management server.
2. Under Identify Your API Proxy:
o Enter a descriptive name for your API, such as weather.
o Enter a Project Base Path.
The Project Base Path is a URI fragment that uniquely identifies the API that is exposed by this API proxy. API
Platform 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) 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.
o Optionally, add a brief description of the API.
3. Optionally, add security and CORS support to your API.
See Adding CORS Support to an API proxy for more information.
4. Select Build
In response, you should see an acknowledgment that your new API proxy was successfully generated. API
Services automatically deploys the newly generated API proxy to the 'test' environment in your organization.
5. The new API is immediately available to be invoked.

Importing API Proxies from an API Proxy Bundle

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.

CUSTOMER SAP API Management, On-Premise Edition


48 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Copying and backing up and API proxy

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.

To copy an existing API proxy to a new API proxy:


1. In the main menu of the management UI, choose APIs to display the API Proxies page.
2. Choose the name of the proxy in the API Proxies table.
3. In the upper-left side of the API proxy detail page, choose Project > Save as New API proxy.
4. Specify the name of the new API proxy.
5. Select Add.

To backup and existing API proxy to an API proxy bundle:


1. In the main menu of the management UI, choose APIs to display the API Proxies page.
2. Choose the name of the proxy in the API Proxies table.
3. In the upper-left side of the API proxy detail page, choose Project > Download Current Revision to download
a ZIP file of the bundle.

Consuming one proxy from another proxy

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 49
You connect target proxies within a TargetEndpoint configuration, using a LocalTargetConnection element,
as described below.
Caution:
When chaining API proxies, take care to avoid "infinite loop" recursive callouts back into the same API proxy,
which could result in system overload.

Connecting proxies by proxy name

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>

Connecting proxies by path

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

CUSTOMER SAP API Management, On-Premise Edition


50 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
</PreFlow>
<PostFlow name="PostFlow">
<!-- PostFlow policies -->
</PostFlow>
<LocalTargetConnection>
<Path>/v1/streetcarts/foodcarts/data-manager</Path>
</LocalTargetConnection>
</TargetEndpoint>

Connecting proxies with the management console

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.

Exposing a SOAP-based Web Service as an API Proxy

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.

Adding Security and CORS support to your API

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 51
Adding Security

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.

Adding Support for CORS

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.

CUSTOMER SAP API Management, On-Premise Edition


52 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Flows Configuration

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.

Attaching Policies to 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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 53
</Request>
<Response/>
</PreFlow>
<Flows/>
<PostFlow>
<Request/>
<Response/>
</PostFlow>
...
</ProxyEndpoint>

About Conditional Flows

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:

• ProxyEndpoint's request pipeline


• TargetEndpoint's request pipeline
• ProxyEndpoint's response pipeline
• TargetEndpoint's response pipeline

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>

CUSTOMER SAP API Management, On-Premise Edition


54 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<Request/>
<Response/>
</PostFlow>
...
</ProxyEndpoint>
Notice that the condition references the request.verb flow variable. A flow variable is named references that
hold state information associated with an API transaction processed by SAP API Management. SAP API
Management defines many state variables that you can reference.
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 conditional flows that map to those API
resources: /reports and /forecasts. When an API call includes one of those resources in the URL, the
condition evaluates to true and the logic attached to the conditional flow is executed.
App developers then access your resources by making requests to a URL in the form:
http://myAPIs.myCo.com/weather/reports
or
http://myAPIs.myCo.com/weather/forecasts

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 &quot;/reports&quot;)</Condition>
<Request/>
<Response/>
</Flow>
<Flow name="Flow-2">
<Condition>(proxy.pathsuffix MatchesPath &quot;/forecasts&quot;)</Condition>
<Request/>
<Response/>
</Flow>
</Flows>
<PostFlow>
<Request/>
<Response/>
</PostFlow>
...
</ProxyEndpoint>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 55
In this example, you reference the proxy.pathsuffix flow variable, which contains the suffix portion of the URL
used to access the API proxy. You can then attach different policies to the conditional flow for each resource.

Adding a Conditional Flow

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>

CUSTOMER SAP API Management, On-Premise Edition


56 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
</Flows>
<PostFlow name="PostFlow">
<Request/>
<Response/>
</PostFlow>

Flow Variables and Conditions

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.

Configuring Conditional Statements

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 57
Imagine that you need to create a conditional statement that will cause a policy to be enforced only when a
request message is a GET. To create a condition that evaluates the HTTP verb of a request, you create the
conditional statement below. The variable in this condition is request.verb. The value of the variable is GET.
The operator is=.
<Condition>request.verb = "GET"</Condition>
<Condition>request.verb equals "GET"</Condition>
API Platform uses such a statement to evaluate conditions. The example above evaluates to true if the HTTP
verb associated with the request is GET. If the HTTP verb associated with the request is POST, then the
statement evaluates to false.

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>

To create one Flow for GETs and another for POSTs:


<Flows>
<Flow name="ExecuteForGETs">
<Condition>request.verb="GET"</Condition>
</Flow>
<Flow name="ExecuteForPOSTs">
<Condition>request.verb="POST"</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>

CUSTOMER SAP API Management, On-Premise Edition


58 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
</Step>
</Request>
</PreFlow>

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.

Conditionally Converting a Payload from XML to JSON


Let's use a specific example in which you need to transform response message from XML to JSON only for
mobile devices. First, create the policy that will convert the XML-formatted response from the Weather API
into JSON:
<XMLToJSON name="ConvertToJSON">
<Options>
</Options>
<OutputVariable>response</OutputVariable>
<Source>response</Source>
</XMLToJSON>
The policy configuration above tells the API proxy to take the response message, perform a conversion from
XML to JSON with default settings, and then write the result to the new response message. (If you are
converting a request message from XML to JSON, you simply set both of these values to request.)

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 59
Configuring Conditional Behavior

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.

Testing the Conditional Flow


In this sample request, the HTTP User-Agent header is set to Mozilla, causing the conditional statement to
evaluate to true and the conditional flow Convert-for-devices to execute.
$ curl -H "User-Agent:Mozilla" http://<host:port>/weather/forecastrss?w=12797282
or, to pretty print where Python is available:
$ curl -H "User-Agent:Mozilla" http://<host:port>/weather/forecastrss?w=12797282 |
python -mjson.tool
Sample Response:
. . .
"yweather_forecast": [
{
"code": "11",
"date": "12 Dec 2012",
"day": "Wed",
"high": "55",
"low": "36",
"text": "Showers"
},
{

CUSTOMER SAP API Management, On-Premise Edition


60 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
"code": "32",
"date": "13 Dec 2012",
"day": "Thu",
"high": "56",
"low": "38",
"text": "Sunny"
}
]
}
. . .
A request submitted without the User-Agent header, or with a different value than Mozilla, will result in an
XML-formatted response.
$ curl http://{org_name}-test.<host:port>/weather/forecastrss?w=12797282
The unmodified XML response is returned.
Sample Response:
<yweather:forecast day="Wed" date="12 Dec 2012" low="36" high="55" text="Showers"
code="11" /> <yweather:forecast day="Thu" date="13 Dec 2012" low="38" high="56"
text="Sunny" code="32" />

Sample Conditions

Condition Attached to RouteRule


<RouteRule name="default">
<!--this routing executes if the header indicates that this is an XML call. If
true, the call is routed to the endpoint XMLTargetEndpoint-->
<Condition>request.header.content-type = "text/xml"</Condition>
<TargetEndpoint>XmlTargetEndpoint</TargetEndpoint>
</RouteRule>

Condition Attached to a Policy


<Step>
<!--the policy MaintenancePolicy only executes if the response status code is
exactly 503-->
<Condition>response.status.code is 503</Condition>
<Name>MaintenancePolicy</Name>
</Step>

Conditional Flow
<!-- this entire flow is executed only if the response verb is a GET-->
<Flow name="GetRequests">
<Condition>response.verb="GET"</Condition>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 61
<Request>
<Step>
<!-- this policy only executes if request path includes a term like statues-->
<Condition>request.path ~ "/statuses/**"</Condition>
<Name>StatusesRequestPolicy</Name>
</Step>
</Request>
<Response>
<Step>
<!-- this condition has multiple expressions. The policy executes if the response
code status is exactly 503 or 400-->
<Condition>(response.status.code = 503) or (response.status.code = 400)</Condition>
<Name>MaintenancePolicy</Name>
</Step>
</Response>
</Flow>

Sample Operators in Conditions


Here are some examples of operators used to create conditions:
o request.header.content-type = "text/xml"
o request.header.content-length < 4096 && request.verb = "PUT"
o response.status.code = 404 || response.status.code = 500
o request.uri MatchesPath "/*/statuses/**"
o request.queryparam.q0 NotEquals 10
To maintain performance and availability across a diverse base of client apps, it's critical to maintain app traffic
within the limits of the capacity of your APIs and backend services. It's also important to ensure that apps don't
consume more resources than permitted.
SAP API Management provides three mechanisms that enable you to optimize traffic management to minimize
latency for apps while maintaining the health of backend services. Each policy type addresses a distinct aspect of
traffic management. In some cases, you might use all three policy types in a single API proxy.

Mapping Conditional Flows to API Resources

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

CUSTOMER SAP API Management, On-Premise Edition


62 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
methods, but the term method can become overloaded, because a RESTful API also has associated HTTP
verbs (GET, PUT, POST, DELETE) which are also sometimes called methods.
To illustrate API resources, we can use a (very simplified) example drawn from SAP API Management's own
Developer Services API. The following snippet of WADL defines two API resources, /developers and /apps. For
each API resource, it defines two methods, create and list.
<resource path="/developers">
<method id="createDeveloper" name="POST">
</method>
<method id="listDevelopers" name="GET">
</method>
</resource>
<resource path="/apps">
<method id="createApp" name="POST">
</method>
<method id="listApps" name="GET">
</method>
</resource>

How API proxies map to specific backend resources

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 &quot;/reports&quot;) and
(request.verb = &quot;GET&quot;)</Condition>
</Flow>
<Flow name="forecasts">
<Description/>
<Request/>
<Response/>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 63
<Condition>(proxy.pathsuffix MatchesPath &quot;/forecasts&quot;) and
(request.verb = &quot;GET&quot;)</Condition>
</Flow>
</Flows>

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 &quot;/reports&quot;) and
(request.verb = &quot;GET&quot;)</Condition>
</Flow>

Note about default flows

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>.

For more information, see Flows Configuration.

Creating conditional flows to backend resources

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:

CUSTOMER SAP API Management, On-Premise Edition


64 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• Apply management in way that reflects the semantics of your API model
• Apply policies and scripted behavior to individual resource paths (URIs)
• Collect fine-grained metrics for Analytics Services

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.

Select one of the flows to view the API resource configuration:


<Flow name="Apps">
<Description>Apps registered in Developer Services</Description>
<Request/>
<Response/>
<Condition>(proxy.pathsuffix MatchesPath &quot;/apps&quot;)</Condition>
</Flow>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 65
As you can see, API resources are simply conditional Flows that evaluate the URI path of the inbound request.
(The proxy.pathsuffix variable identifies the URI of the request that follows the BasePath configured in the
ProxyEndpoint configuration.)
Each API resource that you define is implemented by a conditional Flow in the API proxy. Once you deploy the API
proxy to the test environment, the following request:

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 &quot;/apps&quot;) and (request.verb =
&quot;POST&quot;)</Condition>
</Flow>

CUSTOMER SAP API Management, On-Premise Edition


66 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Building conditions

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 &quot;/apps(/?)&quot;) and (request.verb =
&quot;POST&quot;)</Condition>

Modeling Hierarchical URIs

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 67
Introduction to Flow Variables

What you'll learn in this topic


This overview topic discusses how to access and use flow variables in SAP API Management API proxies. After
reading this topic, you'll understand:
• What flow variables are
• When and where flow variables are created
• How to reference flow variables
• Flow variable scopes and data types
• How to access flow variables in policies
• How to access flow variables JavaScript and Node.js code
• How to create custom flow variables

What are flow variables?

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.

How are flow variables used?

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

CUSTOMER SAP API Management, On-Premise Edition


68 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
programming. For example, a policy to return a fault may execute only when a particular flow variable is set.
Finally, you can get and set flow variables in a Node.js target application.

Let's look at examples of how variables are used in each of these contexts.

Flow variables in policies

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.

Flow variables in conditional flows

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 69
<Name>VerifyApiKey</Name>
</Step>
</Request>
</PreFlow>
Now, you might wonder, where do variables like request.verb, client.ip, and system.time come from?
When are they instantiated and populated with a value? To help you understand when variables are created and
when they're available to you, for more information, see Understanding flow variable scope.

Flow variables in JavaScript code called with the


JavaScript policy

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.

Flow variables in Node.js code

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');

http.createServer(function (request, response) {


sap.setVariable(request, "custom.foo", "Bar");
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);

CUSTOMER SAP API Management, On-Premise Edition


70 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
console.log('Server running at http://127.0.0.1:8124/');

Understanding flow variable scope

Variable scope is related to the flow or overall "life cycle" of an API proxy call.

Visualizing the flow of an API proxy

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.

How variable scope is related to proxy flow

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 71
Note
After a flow variable is populated within its given scope, it remains available through the rest of the proxy
flow life cycle. If you try to access a variable that is not yet in scope, you will receive an error or a NULL
value.

Variable scope Where these variables are populated

proxy request The ProxyEndpoint request segment

target request The TargetEndpoint request segment

target response The TargetEndpoint response segment

proxy response The ProxyEndpoint response segment

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>

CUSTOMER SAP API Management, On-Premise Edition


72 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
This policy simply copies the request object and assigns it to the response object. But where should this policy
be placed in the proxy flow? The answer is that it must be placed on the TargetEndpoint response, because the
scope of the response variable is "target response."

Referencing flow variables

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 73
Data type of flow variables

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.

Using flow variables in policies

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.

CUSTOMER SAP API Management, On-Premise Edition


74 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Working with flow variables in JavaScript code

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.

var org = context.setVariable('organization.name.myorg', value);

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.

Accessing flow variables in Node.js applications

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.

What you need to remember


Here are a few important things to remember about flow variables:
• Some "out-of-the-box" variables are instantiated and populated automatically by the proxy itself. These are
documented in Understanding flow variable scope.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 75
• You can create custom variables that are available for use in the proxy flow. It's possible to create variables
using policies like AssignMessage and JavaScript, and in Node.js code.
• Variables have scope. For example, some variables are automatically populated when the first proxy receives
a request from an app. Other variables are populated in the response flow segment of the proxy. These
response variables remain undefined until the response segment executes.
• When policies execute, they can create and populate policy-specific variables. The documentation for each
policy lists all of these relevant policy-specific variables.
• Conditional flows typically evaluate one or more variables. You need to understand variables if you want to
create conditional flows.
• Many policies use variables as input or output. Perhaps a variable that is created by one policy is later used by
another.
• You can get and set many flow variables from within Node.js, straight JavaScript, or Java code executing on
SAP API Management.

CUSTOMER SAP API Management, On-Premise Edition


76 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Reusable Shared Flows

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 77
Developing a shared flow

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.

Here are the high-level steps for developing a shared flow:


1. Figure out what the shared set of features should be.
For example, you might want to combine traffic management features, including suppressing traffic spikes.
That way, you can manage their configuration outside the workflow of those implementing line-of-business
logic.

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

CUSTOMER SAP API Management, On-Premise Edition


78 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
3. Deploy the shared flow to the environment before deploying proxies or shared flows that will consume it. You
deploy a shared flow in the same way you deploy an API proxy.
A shared flow must be in the same org and deployed to the same environment as the API proxies and other
shared flows that consume it. Deploying the shared flow before the proxies makes it possible to resolve the
proxy's dependency on the shared flow at deploy time.

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 79
2. On the API proxy's Trace tab, begin tracing the API proxy.
3. Send a request to a proxy endpoint in the API proxy. The flow from the endpoint must include the Flow
Callout policy that calls out to the shared flow.
4. On the Trace tab, examine the flow from the API proxy to the shared flow.
Notice that in tracing, the shared flow is represented as a set of steps or policies enclosed in a grey box.
Icons representing Flow Callout policies precede shared flows.

Creating a shared flow with the SAP API Management


Edge management console

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.

o Create a shared flow from existing sources by uploading a flow bundle.


1. Select Shared Flow Bundle to specify a .zip file containing the artifacts you want in the new flow.
A shared flow bundle contains the source artifacts of a shared flow. For example, if you were to
download a shared flow from the management console, you'd have a .zip file with the flow bundle.
2. Click Next.
3. Click Choose File to browse for the .zip file containing the shared flow sources you want to import.
4. In the Shared Flow Name box, enter a name for the imported flow. 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.

CUSTOMER SAP API Management, On-Premise Edition


80 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
5. Click Next.
6. Click Build to build the new flow from the sources you're importing.

Calling a shared flow from an API proxy or shared


flow

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.

Policy Attachment and Enforcement

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 81
format to another XML format. They also enable you to parse messages, to generate new messages and to
change values on outbound messages. Mediation policies also interact with basic services exposed by API
Platform, enabling you to retrieve data about apps, developers, security tokens, and API products at runtime.

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.

Configuring and Attaching Policies

Adding policy-based capabilities to an API proxy is a two-step process:


1. Configure an instance of a policy type.
2. Attach the policy instance to a Flow.
The diagram below shows the relationship between policies and Flows. As you can see, a policy is attached to a
Flow as a processing "Step". To configure the desired behavior for your API, you need to understand a little bit
about Flows. (This topic was covered earlier in Flows Configuration.)

One type of policy that is commonly used is SpikeArrest. SpikeArrest prevents sudden increases in message
traffic that might swamp your backend services.

To attach a policy to a Flow:


1. Select an API proxy and navigate to the Develop view.
2. In the API Proxy Editor, select the New Policy drop-down menu.

CUSTOMER SAP API Management, On-Premise Edition


82 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
A categorized list of the available policy types displays.

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.

The New Policy form provides the following options:


• Display Name: A unique name for this policy. The UI will generate a default name, but it is advisable to create
a descriptive name for the policy. This will ensure that other developers in your organization have an easy
time understanding what the policy is intended to do. The UI changes spaces to dashes, changes consecutive
dashes to a single dash, and removes characters that are not alphanumeric, such as dashes, underscores,
and percent signs.
• Attach Policy: By selecting this checkbox, you will cause the policy to be attached to the specified Flow when
the policy is created, that is, when you select Add. Deselect this box if you do not want to attach the policy yet.
• Flow: Displays a drop-down list of Flows in this API proxy. Select the Flow to which the policy should be
attached. Four default Flows are available. (If you added conditional Flows to your API proxy, they will display
here as options.) To learn more about Flows, see Flows Configuration.
• Segment: Each Flow has a request and response 'segment'. Select the radio button for the segment to which
you want to attach the policy. It's important to attach a policy to the right Flow and segment.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 83
Recommendation
Of course, if you deselect the Attach Policy checkbox, the policy won't be attached to a Flow. The policy
will be created, but it won't be enforced. You might do this if you simply want to configure a policy and
later decide its attach points. You can attach the policy later by selecting it in the Navigator view and then
choosing Attach Policy.)
5. When you finish configuring the policy, select Add
The policy is attached to the Flow that you selected.
6. After you select Add, you’ll see the policy displayed in the Designer view for the PreFlow of the default
ProxyEndpoint. The Code view, which displays the XML for the newly attached policy, displays below
the Designer view of the Flow. Note that the UI has generated an instance of the policy that contains a set of
reasonable default values.

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.

CUSTOMER SAP API Management, On-Premise Edition


84 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Attaching and Configuring Policies in XML Files

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 85
Recommendation
Except for name, you rarely need to modify the default settings for these policy attributes. For this
reason, and for clarity, they are often excluded from the policy samples in the documentation.
In the example above, the elements Allow, Interval, and TimeUnit are specific to the Quota policy. These
elements provide settings that API Platform enforces on behalf of an API.

Attaching a Policy to a ProxyEndpoint or


TargetEndpoint Flow

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>

CUSTOMER SAP API Management, On-Premise Edition


86 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<RouteRule name="default">
<TargetEndpoint>default</TargetEndpoint>
</RouteRule>
</ProxyEndpoint>
You must modify this configuration so that the ProxyEndpoint enforces a Quota policy (as a processing Step)
before the API proxy performs any other processing. If a developer has exceeded a Quota, you don't want to
waste any computational resources on additional requests.
To enforce this configuration, you attach a processing Step to the request PreFlow as follows:
<ProxyEndpoint name="default">
<PreFlow>
<Request>
<Step><Name>QuotaPolicy</Name></Step>
</Request>
</PreFlow>
<HTTPProxyConnection>
<BasePath>/weather</BasePath>
<VirtualHost>default</VirtualHost>
</HTTPProxyConnection>
<RouteRule name="default">
<TargetEndpoint>default</TargetEndpoint>
</RouteRule>
</ProxyEndpoint>
Sometimes, you require a policy to execute after the ProxyEndpoint has performed all processing. To do so,
attach a policy to the PostFlow request path. The following is a sample request PostFlow attachment. This
policy would execute on the request message after all of the policies in the PreFlow execute.
<PostFlow>
<Request>
<Step><Name>QuotaPolicy</Name></Step>
</Request>
</PostFlow>
The following is a sample response PostFlow attachment. This policy would execute on the response
message. (The ProxyEndpoint response PostFlow is the final processing phase before the response is
returned to the requesting client app.)
<PostFlow>
<Response>
<Step><Name>QuotaPolicy</Name></Step>
</Response>
</PostFlow>

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 87
when the ProxyEndpoint receives a request from a client app, and before any additional processing takes
place.

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.

Deploying Policy Changes

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.

Verifying Policy Enforcement

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.

Policy-Based Fault Handling

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>

CUSTOMER SAP API Management, On-Premise Edition


88 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<FaultRules>
<Name>QuotaPolicy</Name>
</Step>
In the example above the Policy named QuotaLimitAlertPolicy would typically be an AssignMessage Policy
that generates a custom response message.
For more on fault handling, see Fault handling

Best Practices: Common Policy Sets

To meet basic management requirements, API proxies usually enforce the following policies:

Basic API Key Validation

ProxyEndpoint Request Flow:


1. SpikeArrest
2. XMLThreatProtection or JSONThreatProtection
3. API key validation
4. Quota
5. ResponseCache

ProxyEndpoint Response Flow:


1. ResponseCache

Basic Transformation: JSON to XML

Request Flow:
1. SpikeArrest
2. JSONThreatProtection
3. API key validation
4. Quota
5. JSONToXML

Response Flow:
1. XMLToJSON
2. ResponseCache

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 89
Rate-Limiting

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.

Concurrent Rate Limiting

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.

CUSTOMER SAP API Management, On-Premise Edition


90 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Persistence

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, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 91
with the variables that you define in caching policies. API Platform also exposes a RESTful API for managing
Cache resources.
Common uses of Cache include temporary storage of:
• Session IDs for session management
• Credentials used for our outbound calls (such as API keys or OAUth access tokens)
• Response content that must be paginated for apps

HTTP/1.1 compliant caching

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 \

CUSTOMER SAP API Management, On-Premise Edition


92 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
'{
"entry" : [ {
"name" : "staging",
"value" : "stage.apifactory.com"
} ],
"name" : "URLs"
}' \
http://<host:port>/v1/o/{org_name}/keyvaluemaps \
-u myname:mypass
See Persist data using KeyValueMap in the Policy document.

Cache Versus Key/Value Map

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.

HTTP Response Caching

About HTTP/1.1 Response Caching

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, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 93
Caching in SAP API Management

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.

Enabling HTTP/1.1 Response Caching

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.

CUSTOMER SAP API Management, On-Premise Edition


94 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
The Cache-Control Response Header

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.

About Cache-Control Header Support

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.

Support for Cache-Control Response Header


Directives

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.

Cache-Control directive How SAP API Management processes the directive

Public SAP API Management caches the origin response,


even when other directives indicate otherwise. Per
the HTTP/1.1 specification, the only exception to this
rule is if the response includes an Authorization
header.

Private This directive is not supported by SAP API


Management. If this directive is received, the origin
response is not cached. Any field names are ignored.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 95
Cache-Control directive How SAP API Management processes the directive

no-cache SAP API Management caches the origin response,


but it must be revalidated with the origin server
before being used to satisfy any subsequent client
requests. This rule allows the origin to return a 304
Not Modified response in order to indicate that the
response should be returned from cache, thus saving
the processing required to return the entire response.
If the origin server returns a full response, it replaces
the existing cache entry. Any field names specified
with this directive are ignored.
Note: The HTTP/1.0 header, Pragma: no-cache is
treated as equivalent toCache-Control: no-cache.

no-store Not supported.

no-transform Not supported.

must-revalidate Not supported. All cache entries are deleted by SAP


API Management as soon as they expire.

proxy-revalidate Not supported. All cache entries are deleted by SAP


API Management as soon as they expire.

max-age The response is cached for the specified number of


seconds.
Note: This directive overrides any expiration specified
in the Expires header and the ResponseCache policy.
See also Reduce latency using ResponseCache.

s-maxage The response is cached for the specified number of


seconds.
Note: This directive overrides any expiration specified
in the Expires header and the ResponseCache policy.
See also Reduce latency using ResponseCache

cache-extension Not supported.

The Expires Response Header

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.

CUSTOMER SAP API Management, On-Premise Edition


96 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Recommendation
When the UseResponseCacheHeaders flag in the ResponseCache policy is set to true, theCache-
Control directives max-age and s-maxage take precedence over and override the behavior of
the Expires header.
Acceptable date formats for the Expires header are described in the HTTP/1.1 specification. For example:
Expires: Thu, 01 Dec 1994 16:00:00 GMT
For detailed information on HTTP date/time formats, see "Date/Time Formats" in the HTTP/1.1 specification.
For more information on Expires header, see "Header Field Definitions" in the HTTP/1.1 specification.

Entity Tag Support

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.

If-Match Request Header Support

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 97
If-None-Match Request Header Support

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.

The If-Modified-Since header

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.

Handling Compressed and Uncompressed Data

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.

CUSTOMER SAP API Management, On-Premise Edition


98 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
How Cache Keys are Generated?

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.

Which Response Codes are Cached?

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 99
Types of errors

An API proxy can encounter the following categories of errors:


• Messaging: Failures arising while driving the message flow, not including policy errors, such as routing
failures
• Policy: Failures arising while processing any policies
• Transport: Failures occurring in the transport layer, such as HTTP errors due to protocol level failures or SSL
errors
• System: Failures in the underlying system, such as out of memory errors
For more information on these errors, see Fault Taxonomy below.

Controlling how a policy reacts to an error

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.

Creating fault rules

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.

CUSTOMER SAP API Management, On-Premise Edition


100 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Very typically it will be a single AssignMessage policy that overrides the default message generated for a fault
and inserts a customized error message. Usually FaultRules do not and should not themselves use RaiseFault
directly. The fault has already been raised. The execution is already in the Error flow. Therefore there is no
need to use RaiseFault to raise a new fault.
Attach fault rules to the following entities in an API proxy configuration:
• ProxyEndpoint: Enables fault handling for all errors that occur in the ProxyEndpoint request and response
flows.
• TargetEndpoint: Enables fault handling for all errors that occur in the TargetEndpoint request and response
flows.

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.

The basic structure of a FaultRule is shown below:


<FaultRules>
<FaultRule>
<Step>
<Name>{policy_name}</Name>
</Step>
<Condition>{(conditional statement)}</Condition>
</FaultRule>

<FaultRule>
...
</FaultRule>
</FaultRules>

OR

<FaultRules>
<FaultRule>
<Step>
<Name>{policy_name}</Name>
<Condition>{(conditional statement)}</Condition>
</Step>
</FaultRule>

<FaultRule>
...
</FaultRule>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 101
</FaultRules>

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.

Specifying the condition on a fault rule

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>

CUSTOMER SAP API Management, On-Premise Edition


102 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<Condition>(fault.name = "InvalidApiKey")</Condition>
</FaultRule>
</FaultRules>
</ProxyEndpoint>
This fault rule executes if an error code InvalidApiKey is thrown by the VerifyApiKey policy.
One common configuration of an API proxy is to use the Quota policy to set the number of requests that an app is
allowed to submit to an API proxy over a time period. If the app exceeds the allowed quota, then the Quota policy
issues an error where the the value of the code field is QuotaViolation. You can use the following condition in a
fault rule to detect the quota error:
<FaultRule name="quota_rule1">
<Step>
<Name>{policy_name}</Name>
</Step>
<Condition>(fault.name = "QuotaViolation")</Condition>
</FaultRule>

Note
If multiple fault rules have a condition that evaluates to true, then the last of those fault rules executes.

Adding policies to a fault rule

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:

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 103
The example below shows a typical RaiseFault policy configuration:
<RaiseFault name="fault_invalidkey">
<FaultResponse>
<Set>
<Payload contentType="text/plain">Contact support at
[email protected].</Payload>
<StatusCode>401</StatusCode>
<ReasonPhrase>Unauthorized</ReasonPhrase>
</Set>
</FaultResponse>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</RaiseFault>

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>

CUSTOMER SAP API Management, On-Premise Edition


104 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
</ProxyEndpoint>
When you deploy the configuration above, the API proxy will execute the RaiseFault policy
called fault_invalidkey whenever an app presents and invalid API key.

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

Defining the custom error message returned from a


fault rule

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 105
<Payload contentType="text/plain">You have attempted to access a resource
without the correct authorization.
Contact support at [email protected].</Payload>
<StatusCode>401</StatusCode>
<ReasonPhrase>Unauthorized</ReasonPhrase>
</Set>
</FaultResponse>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</RaiseFault>

This response includes:


• The payload containing the error message and an email address for contacting support.
• The HTTP status code returned in the response.
• The reason phrase, which is a short description of the error.
In a fault response, you can also use the Assign Message policy to set the <Payload>, <StatusCode>,
and <ReasonPhase> tags.

Configuring Default Fault Rules

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

CUSTOMER SAP API Management, On-Premise Edition


106 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
serves the dual purpose of providing developer-friendly information while also obfuscating backend URLs or
other information that might be used to compromise the system.
For example:
<ProxyEndpoint name="MyProxyEndpoint">
<DefaultFaultRule name="GenericFaultHandler">
</DefaultFaultRule>
....
</ProxyEndpoint>
You customize the behavior of the DefaultFaultRule by attaching one or more Policies as processing Steps.
<DefaultFaultRule name="GenericFaultHandler">
<Step><Name>ReturnGenericFaultMessage</Name></Step>
<AlwaysEnforce>true</AlwaysEnforce>
</DefaultFaultRule>
The AlwaysEnforce element is provided to enable DefaultFaultRules to execute even when other FaultRules
in an API proxy Flow have executed. When the AlwaysEnforce element is set to true, the FaultRule is always
enforced, even if fault handling has executed in a previous processing phase.

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 107
rule to invoke the following AssignMessage policy. This policy writes the fault.name value to a header
named DefaultFaultHeader in the response:

<AssignMessage async="false" continueOnError="false" enabled="true"


name="DefaultFaultRule">
<DisplayName>DefaultFaultRule</DisplayName>
<Set>
<Headers>
<Header name="DefaultFaultHeader">{fault.name}</Header>
</Headers>
</Set>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>
You can then view the header in the SAP API Management trace tool or on the response to see what caused the
error.

Handling policy faults within the current flow

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:

CUSTOMER SAP API Management, On-Premise Edition


108 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<ProxyEndpoint name="default">
...
<PreFlow name="PreFlow">
<Request>
<Step>
<Name>verify-api-key</Name>
</Step>
<Step>
<Name>FaultInFlow</Name>
<Condition>(verifyapikey.verify-api-key.failed = "true")</Condition>
</Step>
</Request>
<Response/>
</PreFlow>
</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.

Triggering an error by using the RaiseFault policy

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 109
Note that the condition tests for a fault named RaiseFault.

Custom Handling of HTTP Error Codes

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>

CUSTOMER SAP API Management, On-Premise Edition


110 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
</Step>
</Response>

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.

Category Subcategory Fault Name Description

Messaging Failures that occur


during the message flow
(not including policy
failures)

Custom faults {fault_name} Any faults explicitly


handled by the API proxy
using the RaiseFault
policy

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 111
Category Subcategory Fault Name Description

Response codes InternalServerError, HTTP error codes 5xx,


NotFound 4xx

Routing failures NoRoutesMatched Failure in selecting a


named TargetEndpoint
for a request

Classification failures NotFound Failures caused by a


request URI that does
not match any BasePath
for any ProxyEndpoint
configurations (that is,
no API proxies match the
URL in the client app's
request)

Transport HTTP transport-level


errors

Connectivity ConnectionRefused, Failures occur while


ConnectionReset, establishing network or
ConnectionTimeout transport-level
connections

Request validations Faults occur during


ContentLengthMissing,
semantics checks on
HostHeaderMissing
every request

Response validations Faults occur during


semantics checks on
every response

IO errors SSLHandshakeError, Read/write errors at


ReadTimeout, ReadError, client or target
WriteTimeout, endpoints, timeouts, SSL
WriteError, ChunkError errors, and chunked
errors

System Undefined runtime errors

Memory OutOfMemory, Memory-related failures


GCOverLimit

Thread RogueTaskTerminated Failures such as


termination of run-away
tasks

Step Faults for each Step


(Policy) type are defined
in the Policy Reference.

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:

CUSTOMER SAP API Management, On-Premise Edition


112 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• Reason
• User-defined custom attributes

Pattern matching in conditional statements

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.

Simple matching with the Matches operator

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 113
Question: What proxy path suffix will cause SomePolicy to execute? There's only one possibility.
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 "/" 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!

CUSTOMER SAP API Management, On-Premise Edition


114 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Is the Matches operator case sensitive?

Yes. Assume you have a condition like this:


<Condition>(proxy.pathsuffix Matches "/*At")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat

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.

How do I escape characters with the Matches


operator?

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.

Finer control with JavaRegex

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 115
there is no match because "[a-z]" matches exactly ONE alpha character. The expression "[a-z]+" would work,
as would "[a-z]{3}". This matching differs from the usual application of regular expressions in tools like Perl or
grep or Apache's mod_rewrite. JavaRegex uses java.util.regex.Pattern.matches(str), which is defined to
return positive if the entire string (str) matches the pattern. The regex in Perl or mod_rewrite are applied to
"any" part of the string. They return true if the pattern matches anywhere. See the example Matching
arbitrary strings with JavaRegex.
• This section is not intended to be a detailed introduction to regular expressions. The main intent is to illustrate
a few simple examples, and highlight the difference between the Matches and JavaRegex operators. If you'd
like to know more about regular expressions, many resources exist for you to explore.

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.

CUSTOMER SAP API Management, On-Premise Edition


116 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Next, we use the "?" quantifier, which matches the preceeding character once, or not at all.
<Condition>(proxy.pathsuffix JavaRegex "/ca?t")</Condition>

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

Is the JavaRegex operator case sensitive?

Yes. Assume you have a condition like this:


<Condition>(proxy.pathsuffix Matches "/ca?t")</Condition>
API call:
GET http://artomatic-test.apigee.net/matchtest/cat
Does the policy execute? Yes, the regex matches zero or one of the preceeding character, which is "a".

API call:

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 117
GET http://artomatic-test.apigee.net/matchtest/cAt
Does the policy execute? No, because the capital "A" does not match lowercase "a".

Matching path fragments with the MatchesPath


operator

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>

Question: What proxy path suffix will cause SomePolicy to execute?


API call:
GET http://artomatic-test.apigee.net/matchtest/animals
Does the policy execute? No, because condition requires another path element after "/animals", as specified by
"/*".
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 clearly has an element ("/cats") that comes after "/animals"
API Call:
GET http://artomatic-test.apigee.net/matchtest/animals/cats/wild
Does the policy execute? No, because the single asterisk only matches one path element, and this API has more
than one element after "/animals".

CUSTOMER SAP API Management, On-Premise Edition


118 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Now let's use the double asterisk:
<PreFlow name="PreFlow">
<Request>
<Step>
<Condition>(proxy.pathsuffix MatchesPath "/animals/**)</Condition>
<Name>SomePolicy</Name>
</Step>
</Request>
<Response/>
</PreFlow>

Question: What proxy path suffix will cause SomePolicy to execute?


API call:
GET http://artomatic-test.apigee.net/matchtest/animals
Does the policy execute? No, because condition requires at least one following path element specified by "/**".

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 119
<Response/>
</PreFlow>

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

A practical example: Ignore "/" at the end of a path

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/

CUSTOMER SAP API Management, On-Premise Edition


120 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Does the policy execute? Yes. Note that in a regular expression, the "?" character means: match zero or one of the
preceeding character. Therefore, both "/cat" and "/cat/" are matches.
API Call:
GET http://artomatic-test.apigee.net/matchtest/cat/spotted
Does the policy execute? No. The regular expression matches zero or only one occurance of the preceeding
character, and nothing else is allowed.

Matching arbitrary strings with JavaRegex

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 121
Resource Files

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.

These resources can be stored in any of three locations in an organization.


• API proxy: When stored in an API proxy, resources are available only to that API proxy.
• Environment: When stored in an environment (for example, test or prod), the resource is available to any API
proxy deployed in the same environment.
• Organization: When stored in an organization, the resource is available to any API proxy deployed in any
environment.

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

Resource repositories support the following resource types:


• jsc: compiled JavaScript, referenced by policies of type Javascript
• java: Java classes, referenced by policies of type JavaCallout
• py: Python scripts, referenced by policies of type Python
• node: Node.js files, including the main Node.js file, related source files, and module dependencies
• wsdl: WSDL files, referenced by policies of type MessageValidation
• xsd: XML schemas, referenced by policies of type MessageValidation
• xsl: XSLT transformations, referenced by policies of type XSL

CUSTOMER SAP API Management, On-Premise Edition


122 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
The repositories are available at the following URIs, as described in the Resource files API:
/organizations/{org_name}/resourcefiles
/organizations/{org_name}/environments/{environment_name}/resourcefiles
/organizations/{org_name}/apis/{api_name}/revisions/{revision_number}/resources

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

Each request returns a list of resource names.

Sample response:
<List>
<Item>JavaScriptMashUp</Item>
<Item>JavaScriptClient</Item>
</List>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 123
Populating resource repositories

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:

$ curl -X POST -H "Content-type:application/octet-stream" -d \


'request.setHeader("RequestPath", flow.getVariable("proxy.basepath"));' \
https://<host:port>/v1/organizations/myorg/resourcefiles?"name=pathSetter&type=jsc" \
-u email:password

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:

CUSTOMER SAP API Management, On-Premise Edition


124 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<Javascript name='PathSetterPolicy' timeLimit='200'>
<ResourceURL>jsc://pathSetter.js</ResourceURL>
</Javascript>

Then reference the policy in the Endpoint configuration:


<PostFlow>
<Request>
<Step><Name>PathSetterPolicy</Name></Step>
</Request>
<PostFlow>

Adding Java resources

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:

curl -v -u {user}:{password} -H "Content-Type: application/octet-stream" \


-X POST --data-binary @{jar_file} \
"http://{mgmt_server}:{port}/v1/organizations/{org}/resourcefiles?name={jar_file}&type
=java"

curl -v -u {user}:{password} -H "Content-Type: application/octet-stream" \


-X POST -T "{jar_file}" \
"http://{mgmt_server}:{port}/v1/organizations/{org}/resourcefiles?name={jar_file}&type
=java"

curl -v -u {user}:{password} -H "Content-Type: multipart/form-data" \


-X POST -F "file=@{jar_file}" \
"http://{mgmt_server}:{port}/v1/organizations/{org}/resourcefiles?name={jar_file}&type
=java"

Resource name resolution

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 125
Let's say that you have populated the same resource in two different repositories — the organization and the
environment:

$ curl -X POST -H "Content-type:application/octet-stream" -d \


'request.setHeader("RequestPath", flow.getVariable("proxy.basepath"));' \
https://<host:port>/v1/organizations/myorg/resourcefiles?"name=pathSetter&type=jsc" \
-u email:password

$ curl -X POST -H "Content-type:application/octet-stream" -d \


'request.setHeader("RequestPath", flow.getVariable("proxy.basepath"));' \
https://<host:port>/v1/organizations/myorg/environments/prod/resourcefiles?"name=pathS
etter&type=jsc" \
-u email:password
Let's take a scenario where the same resource is available in two repositories, at the organization level and at the
environment 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

When deployed in the environment test, the Policy will resolve:

/organizations/myorg/resourcefiles/jsc/pathSetter

CUSTOMER SAP API Management, On-Premise Edition


126 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Retrieving resources

You can view a resource body by calling the GET method on it:

$ curl -X GET -H "Accept:application/json"


https://<host:port>/v1/organizations/myorg/resourcefiles/jsc/pathSetter" \
-u email:password

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.

PUT operations to a JMS queue


SAP API Management's default JMS integration supports receiving messages from a JMS queue. If you want to do
PUT operations to a JMS queue, use a Java Callout policy.

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 127
Creating a JMS Host

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.

curl –H “Content-Type: application/xml” –u : –X POST


“http://{host}:8080/v1/organizations/environments/jmshosts" –d
“<JMSHost name="jmshost1">
<Description></Description>
<ConnectionFactoryClass>org.apache.activemq.jndi.Active
</ConnectionFactoryClass>
<ConnectionFactory>FooFactory</ConnectionFactory>
<ConnectionURL>tcp://(IP Address):61616</ConnectionURL>
<Context>JmsContext</Context>
<ContextUsername>abc</ContextUsername>
<ContextPassword>password</ContextPassword>
<ConnectionUsername>admin</ConnectionUsername>
<ConnectionPassword>password</ConnectionPassword>
<Connections>10</Connections>
</JMSHost>”

Request payload elements

Name Description

name Name of the JMS host.

Description Description of the JMS host.

ConnectionFactoryClass Provider specific implementation of JMS Connection factory class.

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.

ConnectionURL URL of the JNDI provider.

CUSTOMER SAP API Management, On-Premise Edition


128 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Context Initial JNDI context and values are specific to JMS provider.

ContextUsername User name to access the JNDI context.

ContextPassword Password to access the JNDI context.

ConnectionUsername User name to access the JMS provider.

ConnectionPassword Password to access the JMS provider.

Connection Number of physical TCP connections toward JMS 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

Creating a JMS proxy endpoint

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.

Properties are set on a JMS API proxy as follows:


<ProxyEndpoint name=”default” proxyType="jmsConnection">
<!-- "proxyType” is mandatory if you want to create JMS endpoints -->
<JmsProxyConnection state=”on”>
<JMSHost>defaultHost</JMSHost> <!-- this is the JMS host created in prev section -
->
<Destination type="queue">dynamicQueues/myqueue</Destination>
<MessageSelector></MessageSelector>
<DefaultResponseQueue>dynamicQueues/defaultResponseQueue</DefaultResponseQueue>
<JMSResponseHost>defaultResponseHost</JMSResponseHost>
</JmsProxyConnection>
</ProxyEndpoint>

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 129
Property description

The following table provides the description of all JmsProxyConnection properties that are available for JMS
implementation.

Property name Description Required


?

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”.

JMSHost JMS host defined for the JMS proxy. Yes

Destination Queue path to which the subscribe listens to the messages. Yes

MessageSelector Selector pattern on queues based on JMS headers. No

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.

Setting JMS headers

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>

CUSTOMER SAP API Management, On-Premise Edition


130 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Where to set the header: If the proxy is calling a backend service, the header must be set after the backend
service is called. If there is no backend service, such as when you use a Java callout or another API proxy to put
the message on the response queue, the header can be set anywhere in the flow of the API proxy (the API proxy
you don't want putting the response on the queue).
For more information about API proxy flows, see Configuring flows.

For messages placed in the ResponseQueue:


JMSExpiration - Time in milliseconds after which the message expires.
JMSDeliveryMode - A value of 1 (non-persistent) or 2 (persistent).

Adding CORS Support to an API proxy

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.

Typical Use Case for CORS

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.
},

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 131
error: function(xhr, status, err) {
// This is where we end up!
}
});
});
});
</script>
One solution to this problem is to create an SAP API Management API Platform proxy that calls the Yahoo API on
the back end. Remember that API Platform sits between the client (a browser in this case) and the backend API
(Yahoo Weather). Because the API proxy executes on the server, not in a browser, it is able to call Yahoo Weather
successfully. Then, all you need to do is attach CORS headers to the TargetEndpoint response. As long as the
browser supports CORS, these headers signal to the browser that it's okay to "relax" its same-origin policy,
allowing the cross-origin API call to succeed.
Once the proxy with CORS support is created, you can call the API proxy URL instead of the backend service in
your client-side code. For example:
<script>
var url = "http://<host:port>/v1/my-weather-api/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.
},
error: function(xhr, status, err) {
// This time, we do not end up here!
}
});
});
});
</script>

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

CUSTOMER SAP API Management, On-Premise Edition


132 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Attaching an Add CORS Policy to a new API Proxy

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 133
<Header name="Access-Control-Max-Age">3628800</Header>
<Header name="Access-Control-Allow-Methods">GET, PUT, POST,
DELETE</Header>
</Headers>
</Add>
<IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
<AssignTo createNew="false" transport="http" type="response"/>
</AssignMessage>
Basically, the headers let the browser know which origins it will share its resources with (in this case "all origins"),
which methods it accepts, and so on. You can read more about these CORS headers in the Cross-Origin Resource
Sharing W3C Recommendation.

Adding CORS Headers to an Existing Proxy

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.

Handling CORS Preflight Requests

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

CUSTOMER SAP API Management, On-Premise Edition


134 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<Request/>
<Response>
<Step>
<Name>Add-CORS</Name>
</Step>
</Response>
<Condition>request.verb == "OPTIONS"</Condition>
</Flow>
</Flows>

<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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 135
<Flow name="OptionsPreFlight">
<Request/>
<Response>
<Step>
<Name>Add-CORS</Name>
</Step>
</Response>
<Condition>request.verb == "OPTIONS"</Condition>
</Flow>

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.

Exposing a SOAP Service as an API Proxy

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.

Creating a RESTful API Proxy to a SOAP-Based


Service

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.

CUSTOMER SAP API Management, On-Premise Edition


136 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Basic Steps

1. From the Dashboard, choose + API Proxy.


2. In the Build a Proxy wizard, select SOAP service.
3. Click Next.
4. In the Details page, make these selections. You must click Validate after selecting a WSDL.

In this field do this

WSDL Select the source of the WSDL.


• URL - Enter the URL of the WSDL you wish to use.
• File - Choose a WSDL file on your file system. In cases where there are additional
dependent files, you can select all of them.
• Example URL - Select from a list of WSDLs for publicly available web services.
These are handy for trying out the SOAP/API proxy features of SAP API
Management Edge.

Proxy Name This is name for the proxy you're creating.

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.

Description A brief description of the proxy.

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 137
8. Optionally change the HTTP Method associated with the operation.

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.

About the Final Proxy

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.

CUSTOMER SAP API Management, On-Premise Edition


138 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Note
When you face any issue with the request and response, refer the "SAP NOTE 0002115216".

Creating a Pass-through Proxy to a SOAP-Based


Service

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

1. From the Dashboard, choose + API Proxy.


2. In the Build a Proxy wizard, select SOAP service.
3. Click Next.
4. In the Details page, make these selections. You must click Validate after selecting a WSDL.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 139
In this field do this

WSDL Select the source of the WSDL.


• URL - Enter the URL of the WSDL you wish to use.
• File - Choose a WSDL file on your file system. In cases where there are additional
dependent files, you can select all of them.
• Example URL - Select from a list of WSDLs for publicly available web services.
These are handy for trying out the SOAP/API proxy features of SAP API
Management Edge.

Proxy Name This is name for the proxy you're creating.

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.

Description A brief description of the proxy.

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.

CUSTOMER SAP API Management, On-Premise Edition


140 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
About the Final Proxy

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.

Advanced SOAP-to-REST proxy development

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 141
Streaming Requests and Responses

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.

What is Request and Response Streaming?

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).

When should I enable streaming?

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.

What else should I know about streaming?

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.

How to enable response and request streaming

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.

CUSTOMER SAP API Management, On-Premise Edition


142 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
You can locate these configuration files in the management UI in the Develop view for your proxy. If you are
developing locally, these definition files are in apiproxy/proxies and apiproxy/targets.
This sample shows how to enable both request and response streaming in the TargetEndpoint definition.
<TargetEndpoint name="default">
<HTTPTargetConnection>
<URL>http://weather.yahooapis.com</URL>
<Properties>
<Property name="response.streaming.enabled">true</Property>
<Property name="request.streaming.enabled">true</Property>
<Property name="supports.http10">true</Property>
<Property name="request.retain.headers">User-Agent,Referer,Accept-
Language</Property>
<Property name="retain.queryparams">apikey</Property>
</Properties>
</HTTPTargetConnection>
</TargetEndpoint>
This example shows how to enable response and request streaming in the ProxyEndpoint definition:
ProxyEndpoint name="default">
<HTTPProxyConnection>
<URL>http://weather.yahooapis.com</URL>
<Properties>
<Property name="allow.http10">true</Property>
<Property name="response.streaming.enabled">true</Property>
<Property name="request.streaming.enabled">true</Property>
</Properties>
</HTTPProxyConnection>
</ProxyEndpoint>

3.11 Deploying API Proxies

This topic provides a quick overview of proxy deployment. You can deploy proxies using the Management UI,
command-line scripts, or with APIs.

Deploying API proxies to Environments

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 143
Recommendation
Depending on your role, you may not be able to deploy to all environments. For example, the 'user' role
can only deploy to the test environment. If you're an administrator you can deploy to any environment.
For more information, see Understanding deployment.

Development in Test Environment

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.

CUSTOMER SAP API Management, On-Premise Edition


144 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
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. See Manage caches for an environment.
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. See Call services or APIs using ServiceCallout.
To make API proxy configurations environment-independent, you can also use conditional statements.
Conditional statement built with the environment.name variable can be used to evaluate the current environment
before enforcing a policy or before routing to a URL on the backend.
For more information, see Understanding deployment.

Understanding Deployment

When to deploy a proxy

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.

Where to deploy a proxy

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 145
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.

How to deploy a proxy

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.

What is an API Proxy Revision?

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.

What is an API Proxy Version?

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

CUSTOMER SAP API Management, On-Premise Edition


146 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
the signature of an API and requires developers to modify their code accordingly. Versions are usually reflected
directly in the API proxy's base URI. For example:
• api.company.com/v1/...
• api.company.com/v2/...
• api.company.com/v3/...

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

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.

Deploying Proxies in the UI

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 147
Deployment Options

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.

Deploying and Undeploying an API Revision

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.

CUSTOMER SAP API Management, On-Premise Edition


148 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Deploying multiple revisions in the same environment

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.

Running the SAP API Management Python deploy


tool

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 149
In the following command, substitute the proxy name, your SAP API Management username and password, the
SAP API Management organization and environment, and the path to the directory that contains the API proxy's
"apiproxy" directory:

$python tools/deploy.py -n proxyname -u name:passW -o org -e env -d proxypath -p /

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.

On success you see output in the form:

Writing ./<proxybasedir>/apiproxy/weatherapi.xml to apiproxy/weatherapi.xml


Writing ./<proxybasedir>/apiproxy/proxies/default.xml to apiproxy/proxies/default.xml
Writing ./<proxybasedir>/apiproxy/targets/default.xml to apiproxy/targets/default.xml
Imported new proxy version 1
Environment: test
Revision: 1 BasePath = /
State: deployed

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.

CUSTOMER SAP API Management, On-Premise Edition


150 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• -h: Use the URL of the SAP API Management server and port 8080, as in: https://ms_URL:8080. Or, use the
IP address of the management server, as in https://192.168.11.111:8080.

Configuring and running a deploy shell script

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, press ENTER.

You should then see:


Deploying to test on https://<host>:<port>/ using {myname} on <host>:<port>/ and
{org_name} on <host>:<port>/

If you see the following:

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.

Deploy API proxies using the Management API

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 151
migrate API proxies from one environment to another, as part of a larger automated process that also deploys or
migrates other applications.
The management API 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.
This topic focuses on the set of APIs that are for managing API proxies.

Interacting with the API

The following steps walk you through simple interactions with the APIs.

List APIs in your organization


You can begin by listing all of the API proxies in your organization. (Remember to substitute entries
formyname:mypass and {org_name}.
$ curl -u myname:mypass http://<host:port>/v1/o/{org_name}/apis
Sample Response:
[ "weatherapi" ]

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.

CUSTOMER SAP API Management, On-Premise Edition


152 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Get API 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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 153
Deploying an API to an environment
Once your API proxy is configured to receive and forward requests properly, you can deploy it to one or more
environments. Usually, you iterate on API proxies in 'test' and then, when ready, you 'promote' the API proxy
revision to 'prod'. Often, you will find that you have many more revisions of an API proxy in the test environment,
primarily because you will do much less iteration in the prod environment.
An API proxy cannot be invoked until is has been deployed to an environment. Once you have deployed the API
proxy revision to prod, you can then publish the 'prod' URL to external developers.

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.

How to list environments


Every organization has at least two environments: 'test' and 'prod'. The distinction is arbitrary. The goal is to
provide you with an area to verify that your API proxy is working properly before you open it up to outside
developers.
Each environment is really just a network address, enabling you segregate traffic between the API proxies that you
are working on, and those that are being accessed by apps at runtime.
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.

View environments in an organization


$ curl -u myname:mypass http://<host:port>/v1/o/{org_name}/environments

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.

Deploying API Proxies

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

CUSTOMER SAP API Management, On-Premise Edition


154 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
proxy revisions. Use the direct API calls described below when you need additional control over the deployment
process.
Only one revision of an API proxy can be deployed in an environment at a given time. Therefore the deployed
revision needs to be undeployed. You can control whether the new bundle is deployed as a new revision or
whether it overwrites the existing revision.
First undeploy the existing revision. Using query parameters, specify the environment name and the revision
number of the API proxy you want to undeploy:
$ curl -X DELETE \
http://<host:port>/v1/o/{org_name}/environments/{env-
name}/apis/{api_name}/revisions/{revision_number}/deployments"
-u myname:mypass
Then deploy the new revision. (You can deploy using the same revision number, or you can increment it.)
$ 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" \
-u myname:mypass

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 155
http://<host:port>/v1/o/{org_name}/environments/{env-
name}/apis/{api_name}/revisions/{revision_number}/deployments?"override=true&delay=
15" \
-u myname:mypass

Query Parameter Description

override Default is false (normal deployment behavior: existing revision is undeployed,


then new revision is deployed).
Set to true to override the normal deployment behavior and provide seamless
deployment. The existing revision remains deployed while the new revision is
also being deployed. When the new revision is deployed, the old revision is
undeployed. Use in conjunction with the delay parameter to control when
undeployment occurs.

delay To allow transaction processing to complete on the existing revision before it is


undeployed—and eliminate the possibility of 502 Bad Gateway or 504 Gateway
Timeout errors—set this parameter to the number of seconds you want
undeployment to be delayed. There is no limit to the number of seconds you can
set, and there are no performance ramifications for setting a large number of
seconds. During the delay, no new traffic is sent to the old revision.
Default is 0 (zero) seconds. When override is set to true anddelay is 0, the
existing revision is undeployed immediately after the new revision is deployed.
Negative values are treated as 0 (zero) seconds.

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.

See all deployments of an API Revision


Sometimes it's necessary to fetch a list of all of the currently deployed revisions of an API proxy.
$ curl http://<host:port>/v1/o/{org_name}/apis/weatherapi/revision/1/deployments \
-u myname:mypass
-------------------------------------------------------------------------------------------------------------------------------------------------
{
"aPIProxy" : "weatherapi",
"environment" : [ {
"configuration" : {
"basePath" : "",
"steps" : [ ]
},
"name" : "test",
"server" : [ {
"status" : "deployed",
"type" : [ "message-processor" ],
"uUID" : "90096dd1-1019-406b-9f42-fbb80cd01200"
}, {

CUSTOMER SAP API Management, On-Premise Edition


156 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
"status" : "deployed",
"type" : [ "message-processor" ],
"uUID" : "7d6e2eb1-581a-4db0-8045-20d9c3306549"
}, {
"status" : "deployed",
"type" : [ "router" ],
"uUID" : "1619e2d7-c822-45e0-9f97-63882fb6a805"
}, {
"status" : "deployed",
"type" : [ "router" ],
"uUID" : "8a5f3d5f-46f8-4e99-b4cc-955875c8a8c8"
} ],
"state" : "deployed"
} ],
"name" : "1",
"organization" : "org_name"
}
The response above contains many properties specific to the internal infrastructure of SAP API Management.
The important properties contained in the response are organization, environment, aPIProxy, name, and state. By
reviewing these property values, you can confirm that a specific revision of an API proxy is deployed in an
environment.

See all deployments in the test environment


You can also retrieve the deployment status for a specific environment (including the revision number of the
currently deployed API proxy) using the following call:
$ curl -u myname:mypass
http://<host:port>/v1/o/{org_name}/environments/test/deployments
This returns the same result as above for every API deployed in the test environment

See all deployments in your organization


To fetch a list of all currently deployed revisions of all API proxies in all environments, use the following API
method:
$ curl http://<host:port>/v1/o/{org_name}/deployments -u myname:mypass

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,

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 157
"minorVersion" : 0
},
"contextInfo" : "Revision 1 of application weatherapi, in organization
{org_name}",
"createdAt" : 1357172145444,
"createdBy" : "[email protected]",
"displayName" : "weatherapi",
"lastModifiedAt" : 1357172145444,
"lastModifiedBy" : "[email protected]",
"name" : "weatherapi",
"policies" : [ ],
"proxyEndpoints" : [ ],
"resources" : [ ],
"revision" : "1",
"targetEndpoints" : [ ],
"targetServers" : [ ],
"type" : "Application"
}

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.

CUSTOMER SAP API Management, On-Premise Edition


158 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
You can also read about these configuration elements in the API proxy configuration Reference.

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.

3.12 Building Proxies with Node.js

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 159
Enterprise developers have found many creative ways to integrate Node.js applications into the API platform.
Some common use cases include:
• Build highly customized standalone APIs and backend services.
• Solve complex orchestration and mobile optimization problems using SAP API Management policies with
the advantage of a scriptable target endpoint.
• Build composite services and mashups connecting to different SAP and non-SAP backends.
• Rapidly develop prototypes of new APIs.
As you explore our set of Node.js topics, you will learn how to create API proxies with Node.js and how to deploy
your existing Node.js application in SAP API Management.

Getting started with Node.js

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.

Creating the sample Hello World! API proxy

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.

CUSTOMER SAP API Management, On-Premise Edition


160 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
10. Choose Build.
SAP API Management builds the proxy. When the build completes, the hello proxy appears in the API Proxies
summary page. Select API Proxies from the APIs menu to see the API Proxies summary page, shown below:

Invoking the hello proxy

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!

Viewing and editing the Node.js code

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 161
For example, change the response from Hello, World! to something else, like Hello, Node!, then choose
Save. The proxy is saved and redeployed.
Finally, re-invoke the proxy to verify the change:
$ curl http://{hostname}:{port}/v1/hello
Hello, Node!
Like all Node.js applications, Node.js applications running on SAP API Management run in a single thread of
control. There is no need (and in fact no ability) to start another thread, or synchronize variables between threads.
Since Node.js enforces non-blocking programming, a single script can support thousands of concurrent requests
because the script gives up the CPU whenever it has to wait for something, and it is notified later when it happens.
To use Node.js on SAP API Management, you need to specify a main Node.js script file. This script must be
configured to handle incoming requests, which you typically do by using the http or https modules, creating a
client, and so on. (If the main script is not configured this way, it will simply execute and exit after it is deployed.)
Within SAP API Management, each Node.js application script is started from the beginning when the proxy is
deployed, and stopped when the proxy is undeployed. In between it will wait for new requests and process them.
For more information, see "Invoking an imported Node.js file" in Deploying a standalone Node.js app.

Deploying a Standalone Node.js app

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.

CUSTOMER SAP API Management, On-Premise Edition


162 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
About deploying Node.js code 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.

What does SAP API Management tool do?

When you run the SAP API Managementtool utility with the deploynodeapp option, it:

• Generates an API proxy configuration bundle to house the Node.js application.


• Packages the Node.js application with any Node.js packages installed with NPM (Node Packaged Modules).
• Imports the API proxy configuration bundle to the specified organization on SAP API Management using the
SAP API Management API.
• Deploys the API proxy to an environment.
• Executes the Node.js application on SAP API Management and making it available over the network.

Preparing to use SAP API Management tool

Before you begin, you need to install the SAP API Management tool utility.
You can install SAP API Management tool through npm.

Installation from 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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 163
Note
sudo may be required with the -g option which places the SAP API Management tool command-line
commands in you PATH. If you do not use -g, then you need to add the apigeetool/bin directory to your
PATH manually.
Typically, the -g option places modules in: /usr/local/lib/node_modules/apigeetool on *nix-based
machines.

Deploying a Node.js application to SAP API


Management with SAP API Management tool

To deploy a Node.js application using SAP API Management tool:


1. In a terminal window, cd the root directory of your Node.js application.
2. Execute the SAP API Management tool utility with the deploynodeapp command:
$ apigeetool deploynodeapp -n {A name for your new proxy} -d {The root directory of
your Node.js app} -m {The name of the main Node.js file} -o {Your org name on SAP
API Management} -e {The environment to deploy to} -b {The base URL for your proxy}
-u {Your username on SAP API Management} -p {Your SAP API Management password} -L
{Management Server hostname and port}
For example:
$ apigeetool deploynodeapp -n myNodeApp -d . -m server.js -o myorg -e test -b
myNodeApp -u ntesla -p myPassword -L Management Server hostname and port
3. Check the output in your terminal window. It will look something like this:
Importing new application myNodeApp
Imported new app revision 1
Deploying revision 1
Deployed.
Proxy: "myNodeApp" Revision 1
Environment: test BasePath: /myNodeApp
Status: deployed
If you see "Status: deployed", that's it. Everything went smoothly. Your Node.js app is wrapped in an API
proxy, deployed to SAP API Management, and it's running and waiting to handle requests. It's ready to be
tested.
4. Test your proxy.

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.

CUSTOMER SAP API Management, On-Premise Edition


164 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
How SAP API Management tool handles dependent
files and modules

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

Basic usage information for SAP API Management


tool

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

Creating a new proxy with existing Node.js files

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 165
This is currently the only way to incorporate an existing local Node.js application into a proxy from the
management UI. This procedure must be performed when you are creating a new proxy.
1. From the API proxy summary page, choose +API Proxy.
2. In the New API Proxy dialog, select Existing Node.js.
3. Use the Choose Files button to select one or more Node.js files to import.

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.

Adding and invoking new Node.js resource files

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.

Adding new Node.js files through the UI


The management UI lets you add additional Node.js source files to a proxy that is on the API platform. You can
create them directly in the UI or import them from your file system. First, let's look at how to do this from the UI.

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.

CUSTOMER SAP API Management, On-Premise Edition


166 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
The new, blank Node.js file opens in the editor. You can cut and paste your code into the file. The file also appears
in the Scripts section of the Navigator.

Importing Node.js files from your file system


To import a Node.js file from your filesystem to the proxy:
1. In the Develop view, select New Script from the New menu.
2. In the Add Script dialog, choose Import Script.
3. Use the file tool to select your Node.js file.
4. The file's name is added to the dialog, but you can change it if you wish.
5. Choose Add. The file appears in the Scripts section of the Navigator and opens in the editor.
6. Choose Save.
If you want to invoke the imported file, an extra step is required, as explained in the next section.

Invoking an imported Node.js file


You can't simply invoke a newly imported or created Node.js file. The reason is that SAP API Management
requires that one Node.js file be the main file. The main file is specified in the <ScriptTarget> element of the
Target Endpoint definition. To specify which file is the main Node.js file, do the following:
1. Under Target Endpoints in the Navigator, choose the name of the target endpoint (usually called default).
2. In the Code editor, edit the <ScriptTarget> element by changing the <ResourceURL> to reflect the name
of the file you wish to be the main Node.js file. For example, if you wanted a file called hello-world.js to be
the main file, you'd enter: node://hello-world.js in the ResourceURL element.
3. Choose Save.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 167
At this point, you can invoke the file with whatever proxy path you used before. For example, we've been looking at
the Hello World! Example, where the base path v1/hellois specified. However, you can change the base path by
editing the Proxy Endpoint.

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!

CUSTOMER SAP API Management, On-Premise Edition


168 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Exporting and Importing a Proxy with Node.js Code

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.

Using the Trace Tool


The trace tool is useful for general proxy debugging. For detailed information on using the trace tool, see Using the
Trace tool.

Printing Console Output


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);

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 169
Using the Trace Tool

The trace tool is useful for general proxy debugging. For detailed information on using the trace tool, see Using the
Trace tool.

Printing Console Output

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);

CUSTOMER SAP API Management, On-Premise Edition


170 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
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.

Understanding Support for Node.js Modules

Which standard Node.js modules are supported?


Use the following table to determine which standard Node.js modules are either supported, not supported, or
partially supported in SAP API Management.

Assert Supported

Buffer Supported

child_process Restricted An exception will be thrown if an attempt is made


to spawn a sub-process. However, "fork" is
supported for spawning sub-scripts.

cluster Disabled The method cluster.isMaster always returns true,


and other methods are not implemented.
See Why the cluster module is disabled.

Crypto Partial support Random and HMAC functionality is supported.


The remainder is unimplemented.

Dns Partial support dns.lookup is supported. All else is not


implemented.

Domain Supported

Dgram Restricted Node.js applications in the SAP API Management


environment will not be able to access services on

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 171
the Internet via UDP due to our network
architecture.

Events Supported

Fs Restricted Filesystem access is restricted to the directory


where the script was launched:
the /resources/nodedirectory. Node.js scripts
may read and write files within this directory, for
instance as a temporary scratch area, but there
are no guarantees as to how long the files will
persist.

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.

https Supported Creating an "https" server behaves identically to


an "http" server. See "Understanding support for
the http and https modules" for more
information.

module Supported

net Restricted Attempts to listen for incoming TCP connections


will generate an exception.

path Supported

module Supported

process Partial support Functionality to manipulate user ID, group


membership, and working directory is not
supported.

punycode Supported

querystring Supported

readline Disabled There is no standard input for scripts running on


SAP API Management.

repl Disabled There is no standard input for scripts running on


SAP API Management.

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.

CUSTOMER SAP API Management, On-Premise Edition


172 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
stream Supported

string_decoder Supported

timers Supported

tls Supported Transport Layer Security (TLS) parameters work


basically the same way they work in regular
Node.js. See Using the TLS (SSL) Node.js module
on SAP API Management for details.

tty Disabled There is no standard input for scripts running on


SAP API Management.

url Supported

util Supported

vm Supported

zlib Supported

Understanding support for the http and https modules

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.

Handling incoming requests


Like other SAP API Management applications, if the proxy application is set up to listen on the secure virtual host,
then it will accept incoming requests using HTTPS.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 173
Handling outgoing requests
In addition to receiving incoming traffic, Node.js applications inside SAP API Management may use the http and
https modules to make outbound requests like any other Node.js application. These modules work just as they
always do inside Node.js.

Understanding support for the tls module

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:

Handling incoming requests


Depending on how virtual hosts are configured for your organization, SAP API Management provides these
options:
If the API proxy is configured to listen on the default virtual host, then it accepts requests over HTTP.

Handling outgoing requests


You can make outgoing requests with the tls module the same way you would normally in Node.js. Basically, you
need to add client-side keys and certificates (.pem files) to the resources/node directory and load them inside
your script. For information on using the tls module and its methods, see the Node.js tls module documentation.

Why the cluster module is disabled

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.

CUSTOMER SAP API Management, On-Premise Edition


174 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Advanced ScriptTarget Configuration

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>

Using the SAP API Management-access module

The SAP API Management-access module lets you access API proxy flow variables and caches from within
Node.js application code.

Obtaining SAP API Management-access

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.

Accessing flow variables

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 175
Methods

getVariable

var result = getVariable(httpRequest, name);

Gets a named variable.

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

setVariable(httpRequest, name, value);

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');

CUSTOMER SAP API Management, On-Premise Edition


176 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
setIntVariable

setIntVariable(httpRequest, name, value);

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');

Accessing the cache

The sap-access module lets you access the SAP API Management distributed cache from your Node.js code.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 177
Methods

getCache

var cache = sap.getCache('cache-name');


Look up a named cache and create it if necessary. The resulting cache uses a pre-defined set of configuration
parameters suitable for most situations.

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

var customCache = sap.getCache('cache-name', { parameter: 'value'} );


Access a custom cache resource specified in a configuration object. For information about how to create a cache
resource, see Manage Caches for an Environment.

Parameters:

cache-name - The name of the custom cache.

{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.

CUSTOMER SAP API Management, On-Premise Edition


178 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
• defaultTtl: Specifies the default time to live for a cache entry, in seconds. If not specified then the default
TTL in the cache resource will be used.
• timeout: How long to wait to fetch a result from the distributed cache, in seconds. The default 30 seconds.
Latency-sensitive applications may wish to reduce this in order to prevent slow response times if the cache
infrastructure is overloaded.

Returns:
A custom cache object.

Example
var sap = require('sap-access');
var customCache = sap.getCache('MyCustomCache',
{ resource: 'MyCustomResource'} );

put

cache.put('key', data, ttl, function(error));


Put data into a cache.

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
});

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 179
get

cache.get('key', function(error, data));


Retrieve data from a cache.

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) {

CUSTOMER SAP API Management, On-Premise Edition


180 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
});

Using the quota service

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();

// Apply a quota of 100 requests per hour


quota.apply({
identifier: 'Foo',
timeUnit: 'hour',
allow: 100
}, quotaResult);

function quotaResult(err, r) {
if (err) { console.error('Quota failed'); }
}

Parameters
The apply() method takes two parameters, an object and a function:

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 181
4. The first parameter is 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 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();

// Apply a quota of 100 requests per hour


quota.apply({
identifier: 'Foo',
timeUnit: 'hour',
allow: 100
}, quotaResult);

// Apply a quota of 500 requests per five minutes


quota.apply({
identifier: 'Bar',
timeUnit: 'minute',
interval: 5,
allow: 500

CUSTOMER SAP API Management, On-Premise Edition


182 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
}, quotaResult);

// Increment the quota by a value of 10


quota.apply({
identifier: 'Foo',
timeUnit: 'hour',
allow: 100,
weight: 10
}, quotaResult);

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.

Using the secure store service

The sap-access module lets you store sensitive data, such as passwords for backend services, in an encrypted
format on SAP API Management.

Running in local mode vs deployed mode

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 183
Determining the mode in which the module is running
To determine which mode you are running SAP API Management-access in:
var access = require('sap-access')
console.log('The deployment mode is ' + access.getMode());
The return value of getMode() tells you whether or not the Node.js application is deployed to SAP API
Management or is running in standalone mode. The method returns one of these two string results:
• SAP API Management - The Node.js application is running on SAP API Management and all functionality is
supported.
• standalone - The Node.js application is running outside the SAP API Management environment, and the
default functionality described at the top of the document takes effect.

Running in deployed mode


When deployed to SAP API Management, variables set by policies are visible to SAP API Management-access, and
variables added or modified by this module's methods are visible to subsequent policies in the proxy flow.
You can find the link of supported variables in the Variables Reference. These variables, and any that you create
with your own names, are visible toSAP API Management-access. Note that some variables are read-only. They
are identified in the Variables Reference.

Running in local mode


In "local mode," you are running your Node.js code outside the context of SAP API Management. In this mode,
most of the the pre-defined flow variables are not accessible within your Node.js code. This table shows the small
subset of flow variables that are available. These variables are supported here in order to support local
development and testing of Node.js applications for SAP API Management.

Variable Read-Only Type Notes

client.received.start.time Yes String Time at which the request was received

client.received.end.time Yes String Time at which the request was received

client.received.start.timestamp Yes Integer Time at which the request was received

client.received.end.timestamp Yes Integer Time at which the request was received

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.

CUSTOMER SAP API Management, On-Premise Edition


184 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Debugging Node.js proxies

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.

Viewing Node.js logs

To view log information about your Node.js application:


1. In the main API proxies page, choose on the proxy you wish to view.
2. In the summary page of the selected proxy, choose Node.js Logs on the right-hand side of the tool bar.

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 185
Using the trace tool

The trace tool is useful for general proxy debugging. For detailed information on using the trace tool, see Using the
Trace tool.

Printing console output

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);

CUSTOMER SAP API Management, On-Premise Edition


186 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
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.

Understanding Support for Node.js Modules

Which standard Node.js modules are supported?


Use the following table to determine which standard Node.js modules are either supported, not supported, or
partially supported in SAP API Management.

assert Supported

buffer Supported

child_process Restricted An exception will be thrown if an attempt is made


to spawn a sub-process. However, "fork" is
supported for spawning sub-scripts.

cluster Disabled The method cluster.isMaster always returns true,


and other methods are not implemented.
See Why the cluster module is disabled.

crypto Partial support Random and HMAC functionality is supported.


The remainder is unimplemented.

dns Partial support dns.lookup is supported. All else is not


implemented.

domain Supported

dgram Restricted Node.js applications in the SAP API Management


environment will not be able to access services on
the Internet via UDP due to our network
architecture.

events Supported

fs Restricted Filesystem access is restricted to the directory


where the script was launched:
the /resources/nodedirectory. Node.js scripts
may read and write files within this directory, for

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 187
instance as a temporary scratch area, but there
are no guarantees as to how long the files will
persist.

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.

https Supported Creating an "https" server behaves identically to


an "http" server. See "Understanding support for
the http and https modules" for more
information.

module Supported

net Restricted Attempts to listen for incoming TCP connections


will generate an exception.

path Supported

module Supported

process Partial support Functionality to manipulate user ID, group


membership, and working directory is not
supported.

punycode Supported

querystring Supported

readline Disabled There is no standard input for scripts running on


SAP API Management.

repl Disabled There is no standard input for scripts running on


SAP API Management.

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

tls Supported Transport Layer Security (TLS) parameters work


basically the same way they work in regular

CUSTOMER SAP API Management, On-Premise Edition


188 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Node.js. See Using the TLS (SSL) Node.js module
on SAP API Management for details.

tty Disabled There is no standard input for scripts running on


SAP API Management.

url Supported

util Supported

vm Supported

zlib Supported

Understanding support for the http and https


modules

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.

Handling incoming requests


Like other SAP API Management applications, if the proxy application is set up to listen on the secure virtual host,
then it will accept incoming requests using HTTPS.

Handling outgoing requests


In addition to receiving incoming traffic, Node.js applications inside SAP API Management may use the http and
https modules to make outbound requests like any other Node.js application. These modules work just as they
always do inside Node.js.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 189
Understanding support for the tls module

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:

Handling incoming requests


Depending on how virtual hosts are configured for your organization, SAP API Management provides these
options:
If the API proxy is configured to listen on the default virtual host, then it accepts requests over HTTP.

Handling outgoing requests


You can make outgoing requests with the tls module the same way you would normally in Node.js. Basically, you
need to add client-side keys and certificates (.pem files) to the resources/node directory and load them inside
your script. For information on using the tls module and its methods, see the Node.js tls module documentation.

Why the cluster module is disabled

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.

CUSTOMER SAP API Management, On-Premise Edition


190 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Advanced ScriptTarget Configuration

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>

3.13 Debug and Troubleshoot

Using a Trace Tool

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.

How to use Trace

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 191
7. If you don't have any live traffic flowing through your proxy, then simply send a request to the API. You can
use whatever tool you wish to send the request, such as cURL, the SAP API Management API console,
Postman, or any familiar tool. Or, you can send the request directly from the Trace tool itself. Just enter the
URL and choose Send.

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.

How to read a Trace

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:

CUSTOMER SAP API Management, On-Premise Edition


192 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Transaction map legend

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 conditional flow that evaluates to true. For an introduction to conditional flows,


See Flows Configuration for more information.

A conditional flow that evaluates to false. For an introduction to conditional flows,


See Flows Configuration for more information.

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.

The backend target called by the API proxy.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 193
The time line indicates how long (in milliseconds) that the processing time took to
complete. Comparing the elapsed time segments helps you isolate the policies that are
taking the longest to execute that are slowing down your API calls.

The Epsilon indicates a time-span smaller than a millisecond.

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.

Understanding the phase details

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.

Phase Detail Description

Proxy Endpoint Indicates which ProxyEndpoint flow was selected for


execution. An API proxy can have multiple named
proxy endpoints.

Request Headers Lists the HTTP request headers.

Request Content Shows the HTTP request body.

Properties Properties represent the internal state of the API


proxy. These are not shown by default.

Variables Read Lists the flow variables that were read by a policy.
See also Introduction to Flow Variables.

CUSTOMER SAP API Management, On-Premise Edition


194 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Phase Detail Description

Variables Read and Assigned Lists the flow variables that were read and assigned a
value by a policy.

Target Endpoint Indicates which TargetEndpoint was selected for


execution.

Response Headers Lists the HTTP response headers.

Response Content Shows the HTTP response body.

PostClientFlow Shows information about the PostClientFlow, which


executes after the request, is returned to the
requesting client app. Only MessageLogging policies
can be attached to the PostClientFlow. The
PostClientFlow is currently used primarily for
measuring the time interval between the start and
end timestamps for the response message.

Debugging with Trace

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.

Selecting View Options

• Choose the view options for the trace session.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 195
Option Description

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.

Show all FlowInfos Represent transitions within a flow segment.

Automatically Compare Selected Phase Compares the selected phase to the previous one.
Turn this off to see only the selected phase.

Show Variables Show or hide variables that were read and/or


assigned a value.

Show Properties Properties represent the internal state of the API


proxy. (Hidden by default.)

Downloading trace results

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.

CUSTOMER SAP API Management, On-Premise Edition


196 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Using Offline Trace Tool

What is the Offline Trace tool?

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.

Downloading a trace session

To download a trace session:


1. Open the Trace Tool, as described in Using the Trace tool.
2. Perform a trace.
3. When the trace is completed, select Download Trace Session.

The downloaded trace is stored in XML format.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 197
Opening the Offline Trace tool

1. Select APIs > API Proxies from the main SAP API Management menu.
2. On the API Proxies page, choose Offline Trace.

Loading a trace file

In the Offline Trace tool, choose Choose File and select a downloaded trace file from your system.

Troubleshooting

Refining message capture using filters

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

CUSTOMER SAP API Management, On-Premise Edition


198 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
causing issues. Then SAP API Management will only record calls with that specific header so you can examine
the results.
• Query parameters - only calls with a specific value of a parameter will be recorded.

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.

HTTP Response Codes

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, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 199
• HTTP 2xx: Any response code in the 200 range means 'success'. In some cases only a 204 HTTP response
code is issued when an operation succeeds. 204 means that the response is submitted with no content,
usually because a DELETE operation succeeded.
• HTTP 401: This is an authorization failure. It means that the credentials that you used to make a request map
to a user who lacks permission to perform the operation. Verify the roles for the account you are using.
• HTTP 403: This is an authorization failure. It means that the username and password combination you are
using is not valid for the organization you specified. To test your credentials, login to management UI using
<host: port>/login. Once logged in check your account settings to see the organization name. In some
situations, you may belong to multiple organizations. Make sure that you are using the correct credentials for
you organization. Check your spelling.
• HTTP 404: The object wasn't found. This is usually happens because of misspelling in your request URL, but
it may also happen if you try to update an object that doesn't exist (for example, the wrong revision of an API).
• HTTP 405: This means 'Method not allowed'. This response code simply means that you, for example, used
the GET verb for an API call that requires the POST verb.
• HTTP 415: Unsupported media type. This error usually occurs on POST or PUT requests when the Content-
typeHTTP header is set to the wrong value. For example, imagine that you POST the following to an API that
only supports JSON:
$ curl -X POST -H "Content-type:text/xml" -d '<SomeXML>'
https://api.company.com/v1/json_service
The result would be an HTTP 415 error.
For GET requests, remember to use the Accept header instead of the Content-type header
.
• HTTP 500: This is an internal server error. It means that you should contact the administrator to resolve the
issue.

Common Client Issues

Using cURL on Windows


All of the example commands use Linux/Unix command line syntax for quoting arguments. A single quote can be
used as a wrapper for double-quote characters inside a pair of single quotes.
If you are using cURL from a Windows command prompt, Windows does not provide such multi-layered quoting.
Under Windows, the outermost quotes must be the double-quote character and quotes within that string must
doubled, two double-quote characters, where the following examples have one.
curl and HTTPS
The management API requires SSL (HTTPS). If you encounter SSL Certificate problems in response to your cURL
commands, you can:
• Update your certs file.
• Use a command line option to specify an alternate certs file.
Protocol https not supported or disabled in libcurl
Usually seen on machines running Windows, This means that you downloaded and installed a version of curl that
did not include the libcurl package. Download a different package from http://curl.haxx.se/download.html, and
make sure it includes libcurl for SSL.

CUSTOMER SAP API Management, On-Premise Edition


200 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
CLASSIFICATION_FAILURE
You may see this error when you submit a request to your API proxy after you deploy it to API Platform. This error
means that API Platform, while attempting to route the request to the appropriate API proxy, cannot find an API
proxy that matches the request URI path. This usually happens because your request URL does not match the
base path for any API proxies currently deployed in the environment. (Note that API Platform validates that all
base paths are unique when a new API proxy is imported or generated.)
o Verify the URI for your API by logging in to the SAP Management UI. Select the link to your API. At the top
of the page, the URI for you API including the base path displays.
o Make sure your API proxy is deployed. Your API proxy may be imported to SAP API Management, but may
not be deployed to an environment. API proxies can only be invoked after they have been successfully
deployed to an environment. (Note that the deploy tool used in the quick start both imports and deploys
your API proxy to the environment you specify.)

Deploy Tool Errors

python: can't open file 'tools/deploy.py': [Errno 2] No such file or directory


The path you have provided to deploy.py is incorrect.
If you see the following result on import, it indicates that you are running the deploy tool from the wrong
directory.
Import failed to /v1/organizations/myorg/apis?action=import&name=weatherapi with
status 500:
{
"code" : "messaging.config.beans.ImportFailed",
"message" : "Failed to import the bundle : java.util.zip.ZipException: ZIP file
must have at least one entry",
"contexts" : [ ]
}
To fix this issue, run deploy.py from the base directory of the API Platform samples distribution. In the deploy tool
command, specify the directory that contains the ./apiproxy directory-- in this package that value
is simpleProxy.

View API History

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 201
Retrieving API History

To view the history of an API:


1. Select the API from the summary list on the API Proxies page.
2. On the API detail page, choose Project, and choose API Proxy History.
This displays the history for the API.

The history of the selected API is rendered.

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

CUSTOMER SAP API Management, On-Premise Edition


202 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
4. You can view the request body for update operations by choosing Show in the Request Body column for the
operation.

Retrieving API product history

To view the history of an API product:


1. Select History in the Actions column for the product on the Products page.

This history for the API product is displayed.

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.

3.14 Environment Configurations

Creating and Editing an Environment Cache

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 203
Defining a cache resource

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.

Creating and editing caches

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

Name mycache The name of the cache. Must be unique


in the environment. Reference this
cache from policies that interact with
the cache resource.

CUSTOMER SAP API Management, On-Premise Edition


204 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Property Default
Description Notes
Name Value

Description N/A An optional description of the cache


resource.

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.

Expiration Timeout: The configuration setting (either integer


300 or dateTime) for the selection you
(seconds) made in the Expiration Type dropdown.
Time of Enter time of day in the format
day: HH:mm:ss, where HH represents the
12:00:00 hour on a 24-hour clock. For example,
Date: 14:30:00 for 2:30 in the afternoon.
current For the time of day, the default locale
date (dd- and time zone will vary depending on
MM-yyyy) where the code is running (which isn't
knowable at configuration time).

7. Choose Save.

Creating and Editing an Environment Key/Value Maps

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 205
About scope

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.

Creating and editing environment key/value maps

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.

6. Enter key/value properties as described in the following table.

CUSTOMER SAP API Management, On-Premise Edition


206 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Property Name Default Value Description

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.

Load Balancing Across Backend Servers

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.

Sample TargetServer Configuration:


<TargetServer name="target1">
<Host>1.mybackendservice.com</Host>
<Port>80</Port>
<IsEnabled>true</IsEnabled>
</TargetServer >

TargetServer Configuration Elements

Name Description Default Required?

name The name of the N/A Yes


TargetServer
configuration. The name
must be unique within the
environment.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 207
Name Description Default Required?

Host The host URL of the N/A Yes


backend service.

Port The port on which the N/A Yes


backend service is listening

IsEnabled A boolean that indicates true Yes


whether the TargetServer
configuration is enabled or
disabled. This enables you
to take TargetServers out
of rotation without
modifying the API proxy
configuration. A common
usage would be to write an
app or script that enables
or disables TargetServers
automatically based on
expected capacity
requirements,
maintenance schedules,
etc.

To create a TargetServer in an environment:


$ 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 myname:mypass http://<host:port>/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:
$ curl -H "Content-type:text/xml" -X POST -d \
'<TargetServer name="target2">
<Host>2.mybackendservice.com</Host>
<Port>80</Port>

CUSTOMER SAP API Management, On-Premise Edition


208 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<IsEnabled>true</IsEnabled>
</TargetServer >' \
-u myname:mypass http://<host:port>/v1/o/{org_name}/environments/test/targetservers
Sample Response:
{
"host" : "2.mybackendservice.com",
"isEnabled" : true,
"name" : "target2",
"port" : 80
}
Retrieve a list of TargetServers in an environment:
$ curl -u myname:mypass
http://<host:port>/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's HTTPConnection.

Managing target servers with the UI

You can use the SAP API Management Edge UI to create and manage target servers.

1. Select APIs > Environment Configuration in the management UI.


2. Select the desired environment, such as test or prod.
3. Go to the Target Servers tab.
4. Click Edit.
5. Click + Target Server.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 209
6. Enter a name, host, and port.
7. Be sure Enabled is selected.
8. Click Save.

For example:
• Name: target1
• Host: 1.mybackendservice.com
• Port: 80
• Enabled: Selected
Repeat these steps to add and enable more target servers.

Managing target servers with APIs

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:

$ curl -H "Content-type:text/xml" -X POST -d \


'<TargetServer name="target2">
<Host>2.mybackendservice.com</Host>

CUSTOMER SAP API Management, On-Premise Edition


210 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<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" : "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

Configuring a TargetEndpoint to load balance across


named TargetServers

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 211
The configuration above is the most basic load balancing configuration possible. The load balancer supports three
load balancing algorithms, Round Robin, Weighted, and Least Connection. Round Robin is the default algorithm.
Since no algorithm is specified in the configuration above, outbound requests from the API proxy to the backend
servers will alternate, one for one, between target1 and target 2.

Note
Retries are triggered by I/O exceptions and HTTP time outs. Retries are not triggered by HTTP error
codes (4xx, 5xx).

Setting Load Balancer Options

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

CUSTOMER SAP API Management, On-Premise Edition


212 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
<HTTPTargetConnection>
<LoadBalancer>
<Algorithm>Weighted</Algorithm>
<Server name="target1">
<Weight>1</Weight>
</Server>
<Server name="target2">
<Weight>2</Weight>
</Server>
</LoadBalancer>
<Path>/test</Path>
</HTTPTargetConnection>
</TargetEndpoint>
In this example, 2 requests will be routed to target2 for every 1 request routed to target1.

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 213
<Server name="target2" />
</LoadBalancer>
<Path>/test</Path>
</HTTPTargetConnection>
</TargetEndpoint>

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.

CUSTOMER SAP API Management, On-Premise Edition


214 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Configuring a target server for SSL

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 215
Health Monitoring

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>

HealthMonitor with TCPMonitor Configuration Elements

Name Description Default Required?

IsEnabled A boolean that enables or false No


disables the
HealthMonitor.

IntervalInSec The time interval, in 0 Yes


seconds, between each
polling TCP request.

ConnectTimeoutInSec Time in which connection 0 Yes


to the TCP port must be
established to be
considered a success.
Failure to connect in the
specified interval counts

CUSTOMER SAP API Management, On-Premise Edition


216 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Name Description Default Required?
as a failure, incrementing
the load balancer's
failure count for the
TargetServer.

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>

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 217
HealthMonitor with HTTPMonitor Configuration Elements

Name Description Default Required?

IsEnabled A boolean that enables false No


or disables the
HealthMonitor.

IntervalInSec The time interval, in 0 Yes


seconds, between each
polling HTTP request.

Request Configuration options for N/A Yes


the outbound HTTP
request message sent by
the HealthMonitor to the
TargetServers in the
rotation.

ConnectTimeoutInSec Time, in seconds, in 0 No


which the TCP
connection handshake to
the HTTP service must
complete to be
considered a success.
Failure to connect in the
specified interval counts
as a failure, incrementing
the LoadBalancer's
failure count for the
TargetServer.

SocketReadTimeoutInSec Time, in seconds, in 0 No


which data must be read
from the HTTP service to
be considered a success.
Failure to read in the
specified interval counts
as a failure, incrementing
the LoadBalancer's
failure count for the
TargetServer.

Port The port on which the N/A No


HTTP connection to the
backend service will be
established.

Verb The HTTP verb used for N/A No


each polling HTTP
request to the backend
service.

CUSTOMER SAP API Management, On-Premise Edition


218 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
Name Description Default Required?

Path The path appended to N/A No


the URL defined in the
TargetServer. Use the
path element to
configure a 'polling
endpoint' on your HTTP
service.

Headers A list of one or more N/A No


HTTP headers and their
values that will be
populated on each
polling HTTP request.

Payload The HTTP body N/A No


generated for each
polling HTTP request.
Note that this element is
not required for GET
requests.

Response Matching options for the N/A Yes


inbound HTTP response
message generated by
the polled backend
service. Responses that
do not match increment
the failure count by 1.

ResponseCode The HTTP response code N/A No


expected to be received
from the polled
TargetServer. A code
different than the code
specified results in a
failure, and the count
being incremented for
the polled backend
service. You can define
multiple ResponseCode
elements.

Headers A list of one or more N/A No


HTTP headers and
values expected to be
received from the polled
backend service. Any
HTTP headers or values
on the response that are
different from those

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 219
Name Description Default Required?
specified result in a
failure, and the count for
the polled TargetServer
is incremented by 1. You
can define multiple
Header elements.

Configuring outbound client SSL for mutual


authentication

TargetServers expose 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 complete instructions on configuring outbound client SSL, see Configuring SSL to the Backend Service.

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)

CUSTOMER SAP API Management, On-Premise Edition


220 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
One of the main uses of virtual hosts is to let you customize the domain name of your APIs hosted on SAP API
Management. For example, on a cloud-based version of SAP API Management, the default domain name of an
organization called "myorg" in the prod environment is "myorg-<host>:<port>/". Therefore, to access an API
in that organization, a developer uses a URL in the form:

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.

where <inst-root> is the root directory of your installation.


This script prompts you to create a user, organization, environment, and virtual host.

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

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 221
After running that script, you can access your APIs by using a URL in the form:

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.

Viewing information about a virtual host

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:

$ curl -X GET -H "accept:application/xml" \


https://<host:port>/v1/o/{org}/environments/{env}/virtualhosts \
-u myname:mypass

Sample response:
[

CUSTOMER SAP API Management, On-Premise Edition


222 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
"default",
"secure"
]

To see information about a specific virtual host, use the Get Virtual Host API:

$ curl -X GET -H "accept:application/xml" \


https://<host:port>/v1/o/{org_name}/environments/{env_name}/virtualhosts/default \
-u myname:mypass

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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 223
To use the the Get a Cert from a Keystore or Truststore to view a cert:
$ curl -H 'accept: application/xml' \
https://<host:port>/v1/o/{org_name}/environments/{env_name}/keystores/freetrial/certs/
23-sap-wildcard.<host:port>.crt \
-u myname:mypass

Updating an API proxy after creating a virtual host

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.

CUSTOMER SAP API Management, On-Premise Edition


224 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Building APIs
To use the SAP API Management UI to edit the ProxyEndpoint:
1. Login to the SAP API Management UI.
2. In the SAP API Management UI menu, select APIs.
3. Select the name of the API proxy to update.
4. Select the Develop tab.
5. Under Proxy Endpoints, select default.
6. In the code area:
1. Remove any <VirtualHost> elements for virtual hosts not supported by the API proxy.
2. Add a new <VirtualHost> element with the name of the new virtual host. For example, if the new virtual
host is named MyVirtualHost, add the following tag:

<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.

SAP API Management, On-Premise Edition CUSTOMER


Building APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 225
4 Secure APIs

4.1 Org Administration

What are organization users?

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.

What SAP API Management entities do organization


users work with?

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)

Manage Users and Roles

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.

CUSTOMER SAP API Management, On-Premise Edition


226 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
Viewing User Data

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.

Adding Roles to a User

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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 227
4. Select a role to add.
5. Repeat steps 3 and 4 to add additional roles to the user if you want.
6. Choose Save.

Removing Users from an Organization

To remove a user from an organization, you must be an org administrator.


1. Select the user in the Organization Users table.
2. Choose Remove.

Note
This only removes the user from the current account. If the user is a member of multiple accounts, they
remain in the system.

Editing a user's profile and role

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.

CUSTOMER SAP API Management, On-Premise Edition


228 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
What are roles?

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

You must be an org administrator


You must be an SAP API Management organization administrator to create users and assign roles. Only
organization admins can see and use the Admin menu, which is for managing users and roles.

Users must have SAP API Management accounts


Before you can add an organization user to your org and assign roles, that user must have an SAP API
Management account.

What you need to know about user roles

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:

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 229
• When you create your own account, your role is set automatically to organization administrator in your
organization. If you add users to your organization, you set the user role (or roles) at the time that you add
them.
• When an org admin adds you to an org, your role (or roles) are determined by the administrator. The
organization administrator can later change your role(s) if necessary.
• Users can be assigned more than one role. 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.
• By default, all users associated with an organization can view details about other organization users, such as
email address, first name, and last name.
It's important to understand that user roles are specific to the organization in which they were assigned. An SAP
API Management user can belong to multiple organizations, but roles are organization-specific. For example, a
user can be have the organization administrator role in one org and only the user role in another.

SAP API Management Edge built-in 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.

About the Developer Administrator role

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.

CUSTOMER SAP API Management, On-Premise Edition


230 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
The connection between the portal and your SAP API Management Edge organization is configured in Drupal
under Configuration > Dev Portal in the Drupal admin menu (you must be logged into Drupal as an administrator).
If the Connection Status is shown as "Connection Successful," you won't see the devadmin user in the
configuration. However, if the connection is shown as failed, you would enter the devadmin email address and
password to reestablish the connection.
Don't add real users to the Developer Administrator role. (In fact, the management UI and API shouldn't let you.)
That role should contain only the devadmin user.

Adding roles to users

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.

Default role permissions

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

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 231
If you are an organization admin
Organization admins can see the entire list of permissions for each type of user. Just go to Admin > Organization
Roles. When you choose on a role, it takes you to a table that looks like this:

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.

If you are not an org admin


Although you are not permitted to add or change a user's roles or view the role properties in the UI, you can
choose a role below to see a page that lists the permissions granted to that role.
• Business user
• Operations administrator
• Organization administrator
• Read-only organization administrator
• User

CUSTOMER SAP API Management, On-Premise Edition


232 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
Role 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.

SAP API Management APIs allow these CRUD operations:


• GET: Enables a user to view a list of protected resources or to view a singleton RBAC resource
• PUT: Enables a user to create or update a protected resource (encompassing both PUT and POST HTTP
methods)
• 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.

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.

Creating custom roles

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.

Creating custom roles in the UI

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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 233
What are 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.

Entity collections and instances

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.

Using the management UI to create custom roles

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.

CUSTOMER SAP API Management, On-Premise Edition


234 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
The following screen shot shows part of the New Custom Role dialog. For example, this role is called
WeatherApiRole, and it allows a user to view, edit, and delete an API proxy with the path /weatherapi. In addition,
this user can view trace sessions in both prod and test environements, but can only deploy to the test
environment.

Creating roles with the API

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 new custom role

Create a 'development' role to enable developers to view, create, and update API proxies.

$ curl -u myname:mypass https://<host:port>/v1/o/{org_name}/userroles -H "Content-


type:application/json" -X POST -d'{ "role" : [ { "name" : "development" } ] }'

Add permissions to development role

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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 235
curl -u myname:mypass
https://<host:port>/v1/o/{org_name}/userroles/development/permissions -H "Content-
type:application/json" -X POST -d'{"path" : "/applications","permissions" : [ "post",
"get" ]}'

Create a role: testing

Create a 'testing' role to enable quality engineers to view API proxies and their contents (including, for example,
policies).

$ curl -u myname:mypass https://<host:port>/v1/o/{org_name}/userroles -H "Content-


type:application/json" -X POST -d'{ "role" : [ { "name" : "testing" } ] }'

Add permissions to testing role

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:

{"path" : "/,"permissions" : [ "get" ]}'


{"path" : "/*","permissions" : [ ]}'
{"path" : "/environments","permissions" : [ "get" ]}
{"path" : "/userroles","permissions" : [ "get" ]}

Use the following cURL command to set these permissions:

curl -H "Content-Type:application/json" -u [email protected]:refLecT9 \


-X POST \
http://<ms-IP>:8080/v1/organizations/{org_name}/userroles/testing/resourcepermissions
\

CUSTOMER SAP API Management, On-Premise Edition


236 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
-d '{
"resourcePermission" : [
{
"path" : "/",
"permissions" : [ "get" ]
},
{
"path" : "/*",
"permissions" : []
},
{
"path" : "/environments",
"permissions" : [ "get" ]
},
{
"path" : "/userroles",
"permissions" : [ "get"]
}
]
}'
where <ms-IP> is the IP address or DNS name of the SAP API Management Server.

Add user to testing role

To provision a user with a user role:

$ 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"} ] }'

View APIs as user

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.

$ curl -u [email protected]:secret https://<host:port>/v1/o/{org_name}/apis


$ curl -u [email protected]:secret
https://<host:port>/v1/o/{org_name}/apis/{api_name}/policies

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 237
Create API as user in testing role

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 [email protected]:secret -H "Content-Type: application/json"


https://<host:port>/v1/o/{org_name}/apis -X POST -d'{"name" : "rbacTestApi"}'

Add user to development role

Now provision the user with the 'development' role.

$ 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"} ] }'

Create API as user in development role

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.

$ curl -u [email protected]:secret -H "Content-Type: application/json"


https://<host:port>/v1/o/{org_name}/apis -X POST -d'{"name" : "rbacTestApi"}'

Get user roles for a user

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

CUSTOMER SAP API Management, On-Premise Edition


238 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
4.2 OAuth

This topic offers a basic overview of OAuth 2.0 on SAP API Management.

OAuth 2.0

Introduction to 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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 239
The OAuth 2.0 flow

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.

Terms you should know


• Client -- Also called "the app". It can be an app running on a mobile device or a traditional web app. The app
makes requests to the resource server for protected assets on behalf of the resource owner. The resource
owner must give the app permission to access the protected resources.
• Resource owner -- Also called an "end user". This is generally the person (or other entity) who is capable of
granting access to a protected resource. For example, if an app needs to use data from one of your social
media sites, then you are the resource owner -- the only person who can grant the app access to your data.
• Resource server -- Think of the resource server as a service like Twitter or Facebook, or an HR service on
your intranet, or a partner service on your B2B extranet. SAP API Management is a resource server whenever
OAuth token validation is required to process API requests. The resource server needs some kind of
authorization before it will serve up protected resources to the app.
• Authorization server -- The authorization server is implemented in compliance with the OAuth 2.0
specification, and it is responsible for validating authorization grants and issuing the access tokens that give
the app access to the user's data on the resource server. You can configure "token endpoints" on SAP API
Management, in which case it takes on the role of authorization server.
• Authorization grant -- Gives the app permission to retrieve an access token on behalf of the end user. OAuth
2.0 defines four specific "grant types".
• Access token -- A long string of characters that serves as a credential used to access protected resources.
• Protected resource -- Data owned by the resource owner. For example, the user's contact list, account
information, or other sensitive data.

CUSTOMER SAP API Management, On-Premise Edition


240 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
Where SAP API Management fits in

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).

What are OAuth 2.0 grant types?

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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 241
• client credentials -- Consider using for situations where the client app is acting on its own behalf. That is, the
client is also the resource owner. This grant type is typically used when the app needs to access a backend
data storage service, for example. The app needs to use the service to do its work, and the service is
otherwise opaque to the end user. With this grant type, an app can receive an access token by presenting it's
client ID and client secret keys to the authorization server. No further steps are required. SAP API
Management provides an out-of-the-box client credentials solution that's easy to implement for any API
proxy.

What is an access token?

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:

$ curl -H "Authorization: Bearer UAj2yiGAcMZGxfN2DhcUbl9v8WsR" \


http://myorg-test.<host:port>/v0/weather/forecastrss?w=12797282

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.

Limited Access Through Scopes

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).

CUSTOMER SAP API Management, On-Premise Edition


242 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
Registering an app

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.

Summary of OAuth 2.0 use cases

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:

Use Case Trustworthiness Suggested Description


OAuth 2.0
Authorization
Grant Types

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

Publicly Untrusted apps are written by third-party Authorization Requires user to


available developers who do not have a trusted business code log in to third-party
apps relationship with the API provider. For example, resource provider

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 243
developers who register for public API programs (e.g., Twitter,
should not generally be trusted. Facebook)
App never sees
user's username
and password
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.

OAuth 2.0 vs. API key security

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

Implementing the client credentials grant type

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.

About this topic

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.

CUSTOMER SAP API Management, On-Premise Edition


244 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
Use cases

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.

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 245
Steps in the client credentials flow

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.

1. Client requests an access token


To receive an access token, the client POSTs an API call to SAP API Management with the values for client ID and
client secret obtained from a registered developer app. In addition, the parameter grant_type=client_credentials
must be passed as a query parameter. (However, you can configure the OAuthV2 policy to accept this parameter
in the request header or body).
For example:
$ curl -i -H 'ContentType: x-www-form-urlencoded' -X POST 'https://docs-
test.<host:port>/oauth/accesstoken' -d
'grant_type=client_credentials&client_id=ns4fQc14Zg4hKFCNaSzArVuwszX95X&client_secret=
ZIjFyTsNgQNyxI'

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:

$ curl -i -H 'ContentType: x-www-form-urlencoded' -X POST 'https://docs-


test.<host:port>/oauth/accesstoken' -d 'grant_type=client_credentials' -H
'Authorization: Basic
bnM0ZlFjMTRaZzRoS0ZDTmFTekFyVnV3c3pYOTVYOlpJakZ5VHNOZ1FOeXhJOg=='

2. SAP API Management validates the credentials


Note that the API call is sent to the /accesstoken endpoint. This endpoint has a policy attached to it that validates
the app's credentials. That is, the policy compares the submitted keys with the ones that SAP API Management
created when the app was registered.

3. SAP API Management returns a response


If the credentials are okay, SAP API Management returns an access token to the client. If not, an error is returned.

CUSTOMER SAP API Management, On-Premise Edition


246 © 2014 SAP SE or an SAP affiliate company. All rights reserved. Secure APIs
4. The client calls the protected API
Now, with a valid access token, the client can make calls to the protected API. In this scenario, requests are made
to SAP API Management (the proxy), and it is responsible for validating the access token before passing the API
call along to the target resource server.

Configuring flows and policies

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.

Custom flow configuration


The easiest way to show how the API proxy flow is configured is to show the XML flow definition. Here's an
example API proxy flow designed to process an access token request. For example, when a request comes in and
the path suffix matches /accesstoken, the GenerateAccessToken policy is triggered.
<Flows>
<Flow name="GetAccessToken">
<!-- This policy flow is triggered when the URI path suffix
matches /oauth/accesstoken. Publish this URL to app developers
to use when obtaining an access token using an auth code
-->
<Condition>proxy.pathsuffix == "/oauth/accesstoken"</Condition>
<Request>
<Step><Name>GenerateAccessToken</Name></Step>
</Request>
</Flow>
</Flows>

Configure the flow with a policy


You need to attach a policy to the endpoint, as follows.

Get access token


This policy is attached to the /accesstoken path. It uses the OAuthV2 policy with the GenerateAccessToken
operation specified.

<OAuthV2 name="GetAccessToken">
<Operation>GenerateAccessToken</Operation>
<ExpiresIn>3600000</ExpiresIn>
<SupportedGrantTypes>
<GrantType>client_credentials</GrantType>

SAP API Management, On-Premise Edition CUSTOMER


Secure APIs © 2014 SAP SE or an SAP affiliate company. All rights reserved. 247
</SupportedGrantTypes>
<GenerateResponse/>
</OAuthV2>

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:

$ curl -i -H 'ContentType: x-www-form-urlencoded' -X POST 'https://docs-


test.<host:port>/oauth/accesstoken' -d 'grant_type=client_credentials' -H
'Authorization: Basic
c3FIOG9vSGV4VHo4QzAySVgT1JvNnJoZ3ExaVNyQWw6WjRsanRKZG5lQk9qUE1BVQ'

Attaching the verify access token policy

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.

<OAuthV2 async="false" continueOnError="false" enabled="true"


name="VerifyAccessToken">
<DisplayName>VerifyAccessToken</DisplayName>
<ExternalAuthorization>false</ExternalAuthorization>
<Operation>VerifyAccessToken</Operation>
<SupportedGrantTypes/>
<GenerateResponse enabled="true"/>
<Tokens/>
</OAuthV2>

Calling the protected API

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