SAP API Policies

API policies are rules that execute automatically on every API call that passes through an API proxy. They run before the request reaches the backend (request policies), after the backend responds (response policies), or when errors occur (fault policies). Policies implement security, traffic management, transformation, and mediation without any changes to the backend API itself.

Think of policies like the automated checks at airport security. Every passenger goes through the same sequence: boarding pass check, baggage scan, identity verification. These checks happen the same way every time regardless of the destination flight. API policies work the same way — every API call passes through the same policy chain.

Policy Execution Order

INCOMING REQUEST:
[Caller] → [Request Pre-flow] → [Request Flow] → [Backend API]
               ↓ applies policies in order

OUTGOING RESPONSE:
[Backend API] → [Response Flow] → [Response Post-flow] → [Caller]
                    ↓ applies response policies in order

ON ERROR:
[Any point] → [Fault Rules] → [Default Fault Rule] → [Error response to Caller]

Security Policies

Verify API Key

Checks that the incoming request carries a valid API key. The key must be one issued through the Developer Portal for an active subscription.

Policy configuration:
  API Key Location: Header
  Header Name: X-API-Key

Effect: Requests without a valid key receive HTTP 401 Unauthorized.
Requests with a valid key continue to the next policy.

OAuth v2.0 (Verify Access Token)

Validates that the incoming request carries a valid OAuth 2.0 access token. The token must be issued by the configured authorization server and must not be expired.

Policy configuration:
  Token Location: Authorization Header (Bearer token)
  Token Hint: access_token

Effect: Requests with valid tokens proceed.
Expired or invalid tokens receive HTTP 401 Unauthorized.

Basic Authentication

Decodes the Base64-encoded credentials from the Authorization header. Validates the username and password against a stored user profile or external identity provider.

JSON Threat Protection

Validates incoming JSON payloads for potentially malicious content. It checks for excessive nesting depth, overly long strings, and too many JSON keys — all indicators of JSON injection attacks.

Policy configuration:
  Max Container Depth: 10
  Max Object Entry Count: 50
  Max String Value Length: 5000
  Max Array Element Count: 100

Effect: Oversized or deeply nested JSON is rejected with HTTP 400.
Well-formed reasonable JSON proceeds.

XML Threat Protection

Similar to JSON Threat Protection but for XML payloads. Prevents XML External Entity (XXE) attacks and XML bombs (recursive entity expansion that consumes memory).

Traffic Management Policies

Spike Arrest

Prevents sudden bursts of traffic from overwhelming the backend. Limits the rate at which requests are processed to a smoothed maximum, regardless of how many arrive simultaneously.

Policy:
  Rate: 10pm  (10 per minute)

Effect: If 100 requests arrive in one second, Spike Arrest smooths
them to 10 per minute (one every 6 seconds). Excess requests
receive HTTP 429 Too Many Requests.

Use case: SAP BAPI has a hard limit of processing 10 concurrent
calls. Spike Arrest prevents overloading SAP during peak traffic.

Quota

Enforces cumulative usage limits over a time period per API consumer. Unlike Spike Arrest which controls rate, Quota controls total volume.

Policy:
  Count: 1000
  Interval: 1
  TimeUnit: day
  Identifier: request.header.X-API-Key

Effect: Each API key can make 1,000 calls per day.
After 1,000 calls, subsequent calls receive HTTP 429 until midnight.
Counter resets at midnight every day.

Use case: Basic tier API consumers get 1,000 calls/day.
Premium tier consumers get 50,000 calls/day.

Response Cache

Stores backend responses and returns cached copies for identical subsequent requests. Reduces backend load for frequently called, slowly-changing data.

Policy:
  Cache TTL: 300 seconds (5 minutes)
  Cache Key: request.uri + request.header.Accept

Effect: First call to GET /products goes to SAP (takes 800ms).
Subsequent identical calls return cached response (takes 5ms).
Cache expires after 5 minutes and refreshes from SAP again.

Use case: Product catalog API. Data changes rarely.
Caching serves 1,000 callers from one SAP call instead of 1,000.

Mediation Policies

Assign Message

Sets, changes, or removes headers, query parameters, and the message body in either the request or the response. Use it to:

  • Add a backend authentication header that callers should not need to provide
  • Remove a sensitive response header before returning to the caller
  • Inject a correlation ID into every request for end-to-end tracing

Extract Variables

Reads values from the request (headers, body, query parameters) and stores them in policy variables. Subsequent policies can reference these variables.

Extract from JSON body:
  JSONPath: $.order.customer_id
  Variable Name: customerID

Subsequent Assign Message policy:
  Add header: X-SAP-Customer: {customerID}

JSON to XML / XML to JSON

Converts the request or response between JSON and XML. Use this when the caller speaks JSON but the SAP backend expects XML, or vice versa — the conversion happens transparently inside the proxy.

Fault Rules

Fault Rules execute when a policy throws an error. They let you customize error responses before returning them to callers. Instead of the API Management default error format, return a consistent error structure that matches your API design standards:

DEFAULT API Management error (generic):
{
  "fault": {
    "faultstring": "Invalid ApiKey",
    "detail": { "errorcode": "oauth.v2.InvalidApiKey" }
  }
}

CUSTOM Fault Rule error (developer-friendly):
{
  "error": {
    "code": "AUTH_001",
    "message": "API key is invalid or inactive. Please check your Developer Portal subscription.",
    "timestamp": "2024-05-01T14:32:00Z",
    "requestId": "abc-123-xyz"
  }
}

Attaching Policies to API Resources

Policies attach at different levels:

  • Proxy-level (Pre/Post flow) – Apply to every request/response regardless of which resource or operation is called
  • Resource-level – Apply only when a specific URL path is called
  • Operation-level – Apply only for a specific HTTP method on a specific resource

Apply authentication at the proxy level (all requests must authenticate). Apply quota at the resource level (different resources have different limits). Apply JSON threat protection only on POST and PUT operations (GET requests have no body to threaten).

Leave a Comment

Your email address will not be published. Required fields are marked *