# API Management in depth: proxies, policies, products, keys and quotas

> Design an API proxy a review board can approve, from policy order, products and keys to quotas, caching, versions and analytics, and pick its runtime.

- Course: Orchestrate, Unit 26 · Integration in depth
- Page: https://erpfde.com/topics/api-management-in-depth/
- Updated: 2026-11-29
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

An **API** is a door into a system that another program can use. Calder Pumpworks, the fictional pump maker used across this course, wants to give its distributors' systems a door into its S/4HANA system `CP10`, so they can check their order status without phoning customer service.

Nobody opens that door straight onto S/4HANA. A layer sits in front of it: **API Management**, one capability of SAP Integration Suite. For each API it runs an **API proxy**, a stand-in address that partners call instead of the real system. The proxy checks every call before it passes it on:

- **Who is calling?** A key or a token identifies the partner's application.
- **May they?** The partner only gets the API **products** it subscribed to.
- **How much?** A **quota** caps each partner's calls; a separate limit protects S/4HANA from bursts.
- **What do they see?** Only their own orders, and only the fields that were published.
- **What happened?** Every call lands in analytics.

The decision for a leader is the same as for integration flows: **no API goes to a partner until it passes an agreed design review**. A proxy that "works" in a demo can still show one customer another customer's orders.

### Why it matters to the business

Calder's distributor order status API is new; this topic calls it interface `I14`. Here is what a weak proxy for `I14` does:

- **Data leaks between customers.** If the proxy checks who is calling but not which orders they may see, Hallam Fluid Systems can read Brennock Water Utility's orders. That is a confidentiality breach with two customers at once.
- **One partner stops everyone.** If every partner shares one call counter, a retry bug at Hallam uses up the limit, and Calder's own CRM is refused for the rest of the minute.
- **The wrong system answers.** If the test system's address is typed into the proxy, production calls read test data.
- **Writes nobody planned.** If the product publishes the whole S/4HANA API, a partner can change an order, not just read it.
- **Keys in the wrong place.** If the partner's key is passed on to S/4HANA, it ends up in backend logs that more people can read.

Each of these takes minutes to prevent at design time and weeks to clean up after an incident. The review in this topic catches all of them.

### How SAP does it

As of 29 November 2026, SAP's documentation describes API Management in SAP Integration Suite with **three runtimes** ([SAP](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/api-management-de3fea6.md)):

- **Classic API Management**: a managed cloud runtime for API proxies, with more than 30 policy types for security, traffic and message changes.
- **Integration Cell**: a managed runtime for **API artifacts**, which can hold policies and integration steps in one design. SAP calls this API-centric integration and made it generally available on 5 July 2026, with the MCP gateway for AI agents on the same date ([what's new](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/what-s-new-for-sap-api-management-cloud-foundry-d9d60be.md)).
- **Edge Integration Cell**: the same kind of runtime, run by the customer in a private cloud or on premise.

All three share **Developer Hub**, the portal where partners' developers find products, subscribe and get their keys, and API analytics. Which runtime and features you get depends on your Integration Suite service plan; SAP lists them in SAP Note 2903776, and the [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) lists the editions. Check both before you plan.

### What an API review checks

A review board doesn't need to read the policies. It needs answers to eight questions. Calder uses this table for every API it gives to partners.

| Question | A good answer for `I14` | What goes wrong without it |
| --- | --- | --- |
| Is every caller identified first? | The key or token check is the first step, before cache or anything else | Cached answers reach callers with no key |
| Does each partner see only its own data? | Each application carries its customer number; every read is filtered by it | One customer reads another's orders |
| What exactly is published? | Read access to order status only | Partners can change orders |
| Who runs out first? | A quota per application, plus a separate cap sized to what S/4HANA can take | One partner's bug blocks every partner and Calder's CRM |
| Where are backend credentials? | Stored encrypted, read at runtime | A password in the proxy, visible to anyone who can export it |
| Which system answers? | A connection defined per tenant, production to `S4P` | Production partners read test data |
| How do changes reach partners? | Small fixes as revisions; breaking changes as a new version in the address | Partners break without warning |
| What does analytics show? | Calls and errors per partner | Nobody can say who caused a spike |

> **Note** **For functional consultants.** A partner API changes three things in your work. Each partner's application must be tied to the right customer number, so onboarding a distributor now includes an API step that someone owns. Test cases need a "wrong customer" case: Hallam asking for Brennock's order must fail. And when a field is added to the order status, decide whether partners may see it before it is published.

### Questions to ask

1. Which of our APIs can partners reach today, and which proxy and product sits in front of each?
2. For each partner API, what stops one customer from reading another customer's data?
3. Are quotas counted per partner application, or shared?
4. Is there a limit sized to what S/4HANA can handle, separate from the partners' quotas?
5. Where are the credentials that the proxies use to call S/4HANA, and who can read them?
6. Which runtime do our APIs run on, and does our service plan include the one we want next?
7. How are partners told about a breaking change, and how long does the old version stay?
8. Who approves a new partner application, and who removes it when the partner leaves?

### Common misconceptions

- **"A valid key means the caller may see the data."** A key says which application is calling. Which rows it may see is a separate rule.
- **"A quota protects S/4HANA."** A quota caps a consumer over a period. SAP says to use Spike Arrest, not Quota, to protect the backend from bursts.
- **"Caching only makes things faster."** A cache that doesn't know who is asking can hand one partner another's answer.
- **"We'll just publish the whole API and let partners pick."** Every published operation is a promise and a risk. Publish what the use case needs.
- **"Changing the proxy is harmless; it's only a layer."** A change to a published API can break partners. Compatible changes and breaking changes need different handling.

### Key terms

- **API proxy:** the address partners call; it applies policies and then forwards the call to the real API.
- **Policy:** a ready-made step in the proxy, such as checking a key, counting calls or removing a header.
- **API provider:** the stored connection to a backend system, such as S/4HANA through the Cloud Connector.
- **Product:** a bundle of APIs or resources that partners subscribe to, with its own quota.
- **Application:** a partner's registered consumer; it gets a key and secret and subscribes to products.
- **Developer Hub:** the portal where partners' developers find products, subscribe and get keys.
- **Quota:** a cap on calls per period, ideally counted per application.
- **Spike Arrest:** a rate limit that smooths bursts to protect the backend.

### Check yourself

1. What should decide whether a new partner API goes live?
   - A. A demo in which the partner's system reads one order successfully
   - B. An agreed review of identity, data scope, limits and credentials
   - C. The number of policies the developer attached to the API proxy
   - D. Whether the API was published from SAP's Business Accelerator Hub

   Answer: B. A proxy that works in a demo can still show one customer another customer's orders or block every partner when one has a bug. The review checks those failure cases before partners get a key.

2. Hallam's key is valid. Why can it still be wrong to return the order it asks for?
   - A. Because a valid key only lasts until the end of the current quota window
   - B. Because keys are checked again by S/4HANA before any data is returned
   - C. Because the key says which application calls, not which orders it may see
   - D. Because orders can only be read through Developer Hub, not through a key

   Answer: C. Identifying the caller and limiting its data are two rules. Each application must carry its customer number, and every read must be filtered by it, or Hallam can read Brennock's orders.

3. A retry bug at one distributor blocks Calder's own CRM. What design caused it?
   - A. The CRM and the distributor were published in two separate products
   - B. One quota counter was shared by every application calling the API
   - C. The quota was counted per application instead of per API proxy
   - D. The backend's burst limit was set lower than the distributors' quota

   Answer: B. A shared counter lets one consumer use up everyone's allowance. Counting the quota per application keeps a partner's bug inside that partner's limit.

4. Which control protects S/4HANA itself from a sudden burst of calls?
   - A. A quota per partner application, counted over each calendar day
   - B. A longer cache time so that fewer answers come from S/4HANA
   - C. A Developer Hub approval step for every new partner application
   - D. A rate limit sized to what S/4HANA can take, separate from quotas

   Answer: D. SAP says to use Spike Arrest, not Quota, to protect the backend against spikes. Quotas cap each consumer over a period; the rate limit smooths what reaches S/4HANA.

5. The team wants to rename a field in the order status API. How should it reach partners?
   - A. As a revision, so partners keep the same address and get it at once
   - B. As a new version in the address, with the old one kept for a while
   - C. As a change to the product's description in Developer Hub
   - D. As a new quota so that partners notice the change in their limits

   Answer: B. Renaming a field breaks partners who read it. SAP describes revisions for compatible changes and versions, with the version in the URL, for incompatible ones.

6. Calder plans to let AI agents use the order status API later. What should a leader check first?
   - A. Whether agents can share the distributors' keys to save setup time
   - B. Whether the CRM team agrees to lower its own quota for the agents
   - C. Whether Developer Hub can show the API to agents without a product
   - D. Whether the service plan includes the runtime that the MCP gateway needs

   Answer: D. SAP's MCP gateway can turn API artifacts on Integration Cell into tools for agents, and which runtimes and features you get depends on the service plan in SAP Note 2903776. The runtime choice for the API decides whether that path is open.

## Deep layer

### Mental model

An API proxy is **a pipeline of small checks between two contracts**. On one side is the contract with the consumer: the address, the product, the key, the quota, the fields. On the other is the contract with the backend: the provider, the credential, the rate it can take. Policies are the steps in between, and **their order is part of the design**: a cache placed before the key check answers callers who have no key.

So a proxy review asks three things about every policy: is it there, is it in the right place, and is its scope right (per application, per customer, per backend)? The lab in this topic checks exactly that and replays the same 33 calls through a weak and a reviewed design.

### How it works

#### The anatomy of a proxy

SAP's documentation describes two endpoints in every classic proxy ([Flow](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/flow-08b40d9.md)):

- the **proxy endpoint**, which faces the consumer (its base path, such as `/v1/salesorderstatus`), and
- the **target endpoint**, which faces the backend, usually through an **API provider**.

Each endpoint has a request and a response pipeline. Each pipeline runs a **PreFlow** first, then at most one **conditional flow** (the first whose condition matches), then a **PostFlow**. The proxy's response side can also run a **PostClientFlow** after the answer has gone back, for logging. SAP's guidance is to put security and quota policies in the proxy endpoint's PreFlow, so a call that fails them never reaches the backend. Policies run in the order they are attached.

```mermaid
flowchart LR
  C[Partner system] -->|APIKey| P1
  subgraph PE[Proxy endpoint]
    P1[PreFlow:<br/>key, quota,<br/>customer filter, cache] --> P2[Conditional flow]
  end
  subgraph TE[Target endpoint]
    T1[PreFlow:<br/>strip key, Spike Arrest,<br/>read secret, backend auth]
  end
  P2 --> T1 --> PR[API provider<br/>S4_ORDERS]
  PR -->|Cloud Connector| S4[S/4HANA S4P]
```

#### Policies by job

SAP lists more than 30 prebuilt policy types for classic proxies ([Policy Types](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/policy-types-c918e28.md)). Every policy shares three attributes: `enabled`, `continueOnError` (for a quota, SAP says to keep it `false`) and `async`. Grouped by job:

| Job | Policies | Use in `I14` |
| --- | --- | --- |
| Identify the caller | Verify API Key, OAuth v2.0, Verify JWT, Basic Authentication, SAML Assertion | Verify API Key first in the PreFlow |
| Limit traffic | Quota, Spike Arrest, Reset Quota | Quota per application; Spike Arrest on the target side |
| Protect content | JSON Threat Protection, XML Threat Protection, Regular Expression Protection, Access Control | Threat protection when partners can send bodies (not yet) |
| Change messages | Assign Message, Extract Variables, JSON to XML, XML to JSON, XSL Transform, JavaScript, Python Script | Assign Message removes the `APIKey` header |
| Store and look up | Key Value Map Operations, Populate, Lookup and Invalidate Cache, Response Cache | Encrypted map for the backend password; cache per application |
| Observe and fail cleanly | Statistics Collector, Message Logging, Raise Fault | Customer as an analytics dimension; short error messages |

SAP has decommissioned the Concurrent Rate Limit policy and points to Quota and Spike Arrest instead ([SAP](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/replace-concurrent-rate-limit-policy-with-alternative-policies-b70e0d2.md)).

#### Products, applications and keys

A **product** bundles APIs, or only some of their resources, for consumers. An **application** is the consumer's registration: when a developer creates one in Developer Hub and subscribes it to products, API Management issues an application key and secret. Verify API Key then checks the key on every call and fills flow variables with the application, the developer and the product.

Two details matter for review:

- **Selective publishing.** A product can publish only some resource paths of a proxy. SAP's documentation shows how the product's resource path matches the path after the proxy's base path ([SAP](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/understanding-the-default-behavior-of-an-api-product-for-different-resource-paths-bf2ee80.md)). Publish the reads a partner needs, not the whole service.
- **Product quotas need policies.** Setting a quota on a product doesn't enforce anything by itself. SAP's [Create a Product](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/create-a-product-d769622.md) page says you need Verify API Key and Quota policies on the API; the product's value then takes precedence and can be changed at runtime.

**Custom attributes** carry business context. An admin can create an application on a developer's behalf and give it attributes; policies read them at runtime through Verify API Key, an access token or Access Entity ([Custom Attributes](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/custom-attributes-90a5a6d.md)). Calder puts the distributor's customer number on each application, and the proxy filters every read by it. SAP's limits are 18 attributes, names up to 255 and values up to 1,024 characters.

#### Quota and Spike Arrest are different tools

- **Quota** counts calls per period. By default a Quota policy keeps **one counter**, however many flows use it; its **Identifier** element gives one counter per application or client ([Understanding Quota Counters](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/understanding-quota-counters-cb606e3.md)). Counters belong to one proxy. Quota types decide when counters reset: calendar (from a start time), rolling window, or flexi (from each app's first call). Times are UTC.
- **Spike Arrest** isn't a count but a rate: 6 per minute means one call every 10 seconds, and it isn't distributed across servers. SAP's guidance is to set it to what the backend can handle and not to use it to limit individual clients ([Spike Arrest](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/spike-arrest-bf441dc.md)).

On Integration Cell, SAP's equivalents are the Quota policy (since 31 May 2026 its Identifier is pre-filled with the client ID) and the **Surge Protection** policy.

#### Caching without leaking

Response Cache serves repeated reads from memory. It is attached twice, in the PreFlow and the PostFlow; each object holds up to 512 KB, and error responses are cached too unless excluded ([Response Cache](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/response-cache-8df3fac.md)). The **cache key** decides which requests share an answer: SAP builds it from key fragments that you choose. If the key is only the address, two partners asking for "my orders" at the same address share one answer. Put the application or customer in the key, and attach the cache after the identity and filter steps.

#### Credentials and providers

An **API provider** holds the connection to a backend, including on-premise systems exposed through the Cloud Connector ([API Providers](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/api-providers-42e13b2.md)). Because a provider is defined per tenant, the test tenant's provider can point to `S4Q` and production's to `S4P` while the proxy stays the same. Backend passwords belong in an **encrypted key value map**, read at runtime ([Create a Key Value Map](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/create-a-key-value-map-90d8d41.md)); SAP warns against concurrent writes to environment-scoped maps and against using maps for logs. Since 18 October 2026, an Integration Cell API artifact pointing to an on-premise system can use **principal propagation**, so the backend checks the calling user's own authorizations.

#### Revisions, versions and states

SAP separates two kinds of change ([API Revisions](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/api-revisions-58097ac.md)):

- A **revision** is a compatible change. The URL stays, only one revision runs, and you can compare and restore earlier ones.
- A **version** is an incompatible change. The version is in the URL (`/v2/...`), and several versions run side by side. Once set, version and base path can't be edited.

An API proxy also carries a **state**: Alpha, Beta, Active, Deprecated or Decommissioned. Deprecating needs a date and a successor. SAP states the state is for demarcation only and plays no role in governance, so it doesn't stop calls by itself.

#### Runtimes and the shift to API artifacts

Classic proxies are built in the API portal. **API artifacts** are built in Integration Suite's design area, in packages, and deploy to Integration Cell or Edge Integration Cell ([API-Centric Integration](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/api-centric-integration-cf4b847.md)). Their policy model differs:

- **Authentication** is mandatory, always first and can't be removed. It supports Basic, client certificate and OAuth with SAP's identity service, or tokens from an external OpenID Connect provider such as Microsoft Entra ID.
- **Authorization** checks OAuth scopes, a developer key (the subscription's client ID), or both ([Authorization](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/authorization-6658409.md)).
- Security policies add API validation against an OpenAPI 3.0 description and JSON and XML threat protection; traffic policies are IP Filter, Quota and Surge Protection ([security](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/security-policies-aebf968.md), [traffic](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/traffic-management-policies-165db68.md)).
- **Mediation steps** from Cloud Integration (mapping, routing, calls) sit in the same artifact, and **reusable API artifacts** hold shared logic called through the API Direct adapter.

When SAP's MCP gateway builds an MCP server from an API artifact, that artifact must be an OData or REST API on Integration Cell with OAuth-based authentication, as the [MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) shows. Other sources (an HTTP endpoint, an RFC backend, a remote MCP server) exist, but for an API you already govern, the runtime choice is also a choice about agents.

#### Analytics and limits

API analytics shows traffic, response times and errors on Overview, Health and Usage pages, and keeps data for 6 months, per SAP's [dashboard page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/working-with-the-api-analytics-dashboard-e07e815.md). To see calls per partner, a Statistics Collector policy writes custom dimensions; SAP allows one such policy per proxy. Classic [limits](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/limits-in-api-management-f70f425.md) include HTTPS on port 443 only, 10 MB for non-streamed requests, cache values of 512 KB, OAuth access tokens of at least 180 seconds, and three virtual hosts per tenant by default.

### Build it yourself: review and replay Calder's order status proxy

You will save one script that holds two designs for `I14`: a partner's draft and Calder's reviewed version. The script checks each against 14 rules, then replays the same 33 calls through each and shows what partners and S/4HANA would see. No account, no network, no randomness.

```mermaid
flowchart LR
  A[apim_review.py --init] --> B[proxy_draft.json<br/>proxy_reviewed.json<br/>apps.json, traffic.json]
  B --> C[review: rules A01-A14]
  B --> D[replay: 33 calls]
  C & D --> E[your review notes]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 26](https://erpfde.com/topics/set-up-for-unit-26/). This walkthrough doesn't repeat those steps.

> **Note** New words. A **header** is a named value sent with an HTTP call, such as `APIKey`. **HTTP status codes** say how a call ended: `200` answered, `401` not identified, `403` refused, `404` not found, `405` method not allowed, `429` too many requests. **JSON** is the text format the design files use. A **replay** sends recorded calls through a design to see what happens.

#### What you need

- Your course folder `orchestrate-course` with its `.venv`.
- About 30 minutes. Everything is free.

#### Step 1: Open the course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. Check that `unit26` exists (the Unit 26 setup created it). If not, create it with `mkdir unit26`.

#### Step 2: Save the script

1. In VS Code, right-click `unit26`, choose **New File**, name it `apim_review.py`, paste the code below and save.

```python
"""Unit 26: review and replay an API proxy design for Calder's distributor order status API.

Run from your course folder:
    python unit26/apim_review.py --init                 # write the two designs and the traffic
    python unit26/apim_review.py review draft           # check the partner's draft against rules A01-A14
    python unit26/apim_review.py replay draft           # send the same 33 calls through the draft
    python unit26/apim_review.py review reviewed        # check the reviewed design
    python unit26/apim_review.py replay reviewed        # and replay it

Built-in Python only, no randomness, no account. This is a teaching model of an API proxy's
policy chain, not SAP API Management. Policy names follow SAP's classic API Management policy
types; the design file format, rules, limits, keys and app names are course values. Calder
Pumpworks, Hallam Fluid Systems and Brennock Water Utility are fictional.
Exit code 0 when the review has no FAIL, 2 when it has at least one.
"""
import argparse
import json
import sys
from pathlib import Path

HERE = Path(__file__).resolve().parent / "apim"

# Open sales orders from the order-to-cash topic (fictional), as the stand-in S/4HANA API returns them.
ORDERS = {
    "1000002": {"SoldToParty": "10000002", "CustomerName": "Hallam Fluid Systems", "RequestedDeliveryDate": "2026-10-30", "TotalNetAmount": "24288.00"},
    "1000003": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "RequestedDeliveryDate": "2026-11-02", "TotalNetAmount": "12300.00"},
    "1000004": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "RequestedDeliveryDate": "2026-10-27", "TotalNetAmount": "24600.00"},
    "1000005": {"SoldToParty": "10000002", "CustomerName": "Hallam Fluid Systems", "RequestedDeliveryDate": "2026-10-28", "TotalNetAmount": ""},
    "1000006": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "RequestedDeliveryDate": "2026-10-20", "TotalNetAmount": "4200.00"},
    "1000007": {"SoldToParty": "10000001", "CustomerName": "Brennock Water Utility", "RequestedDeliveryDate": "2026-11-09", "TotalNetAmount": "8400.00"},
}
BACKEND_CAPACITY_PER_S = 10   # course value: what S4P's API can take from this proxy
TENANT_STAGE = "prod"         # the replay runs as the production API Management tenant

APPS = [
    {"app": "HFS-ORDERS", "developer": "Hallam integration team", "key": "calder-lab-key-hfs", "product": "CAL_Distributor_OrderStatus", "attributes": {"customer": "10000002"}},
    {"app": "BWU-PORTAL", "developer": "Brennock IT", "key": "calder-lab-key-bwu", "product": "CAL_Distributor_OrderStatus", "attributes": {"customer": "10000001"}},
    {"app": "CRM-CPUS", "developer": "Calder CRM team", "key": "calder-lab-key-crm", "product": "CAL_Internal_OrderStatus", "attributes": {"customer": "*"}},
]

DRAFT = {
    "name": "draft",
    "proxy": {"name": "SalesOrderStatus", "base_path": "/salesorderstatus", "state": "Active",
              "target": {"kind": "url", "url": "https://s4q-api:443/sap/opu/odata/sap/API_SALES_ORDER_SRV", "system": "S4Q"}},
    "request_preflow": [
        {"type": "ResponseCache", "name": "cache", "key": ["uri"], "ttl_s": 300},
        {"type": "VerifyAPIKey", "name": "verify", "header": "APIKey"},
        {"type": "Quota", "name": "quota", "identifier": None, "limit": 20, "per": "minute"},
        {"type": "RowFilter", "name": "own_orders", "attribute": "customer", "applies_to": ["list"], "fail_closed": False},
    ],
    "target_request": [
        {"type": "BasicAuthentication", "name": "backend_auth", "user": "TU_APIM_ORDERS", "password_source": "literal", "password": "Welcome2026!"},
    ],
    "statistics": [],
    "fault": {"return_backend_body": True},
    "products": [
        {"name": "CAL_Distributor_OrderStatus", "resources": ["*"], "methods": ["*"], "quota": {"limit": 20, "per": "minute"}},
        {"name": "CAL_Internal_OrderStatus", "resources": ["*"], "methods": ["*"], "quota": {"limit": 600, "per": "minute"}},
    ],
}

REVIEWED = {
    "name": "reviewed",
    "proxy": {"name": "CPUS_SalesOrderStatus_v1", "base_path": "/v1/salesorderstatus", "state": "Active",
              "target": {"kind": "api_provider", "provider": "S4_ORDERS", "system_by_stage": {"test": "S4Q", "prod": "S4P"}}},
    "request_preflow": [
        {"type": "VerifyAPIKey", "name": "verify", "header": "APIKey"},
        {"type": "Quota", "name": "quota", "identifier": "client_id", "limit": "product", "per": "minute"},
        {"type": "RowFilter", "name": "own_orders", "attribute": "customer", "applies_to": ["list", "single"], "fail_closed": False},
        {"type": "ResponseCache", "name": "cache", "key": ["uri", "client_id"], "ttl_s": 60},
    ],
    "target_request": [
        {"type": "AssignMessage", "name": "strip_key", "remove_headers": ["APIKey"]},
        {"type": "SpikeArrest", "name": "protect_s4", "rate_per_s": 8},
        {"type": "KeyValueMapOperations", "name": "read_secret", "map": "calder-s4-orders", "encrypted": True},
        {"type": "BasicAuthentication", "name": "backend_auth", "user": "TU_APIM_ORDERS", "password_source": "kvm"},
    ],
    "statistics": [{"type": "StatisticsCollector", "name": "stats", "dimensions": ["customer", "app"]}],
    "fault": {"return_backend_body": False},
    "products": [
        {"name": "CAL_Distributor_OrderStatus", "resources": ["/A_SalesOrder"], "methods": ["GET"], "quota": {"limit": 20, "per": "minute"}},
        {"name": "CAL_Internal_OrderStatus", "resources": ["/A_SalesOrder"], "methods": ["GET"], "quota": {"limit": 600, "per": "minute"}},
    ],
}


def traffic():
    """33 calls in the first minute, then one call a minute later. Seconds are simulated."""
    calls = [
        {"id": "T01", "t": 0, "app": "HFS-ORDERS", "method": "GET", "path": "/A_SalesOrder('1000002')", "note": "Hallam reads its own order"},
        {"id": "T02", "t": 1, "app": None, "method": "GET", "path": "/A_SalesOrder('1000002')", "note": "no key"},
        {"id": "T03", "t": 2, "app": "HFS-ORDERS", "method": "GET", "path": "/A_SalesOrder", "note": "Hallam lists its orders"},
        {"id": "T04", "t": 3, "app": "BWU-PORTAL", "method": "GET", "path": "/A_SalesOrder", "note": "Brennock lists its orders"},
        {"id": "T05", "t": 4, "app": "HFS-ORDERS", "method": "GET", "path": "/A_SalesOrder('1000003')", "note": "Hallam asks for Brennock's order"},
        {"id": "T06", "t": 5, "app": "HFS-ORDERS", "method": "PATCH", "path": "/A_SalesOrder('1000002')", "note": "Hallam tries to change a date"},
    ]
    for i in range(25):   # a retry bug in Hallam's system: 25 reads in 25 seconds, each with a new timestamp
        calls.append({"id": f"T{7 + i:02d}", "t": 6 + i, "app": "HFS-ORDERS", "method": "GET",
                      "path": f"/A_SalesOrder('1000005')?ts={6 + i}", "note": "Hallam's retry loop"})
    calls.append({"id": "T32", "t": 40, "app": "CRM-CPUS", "method": "GET", "path": "/A_SalesOrder('1000004')", "note": "Calder's CRM reads an order"})
    calls.append({"id": "T33", "t": 70, "app": "BWU-PORTAL", "method": "GET", "path": "/A_SalesOrder('1000007')", "note": "Brennock, next minute"})
    return calls


# ---------- review ----------

def policy(design, kind, where="request_preflow"):
    return next((p for p in design[where] if p["type"] == kind), None)


def review(design, apps):
    rows = []

    def add(rule, status, text):
        rows.append((rule, status, text))

    pre = design["request_preflow"]
    first = pre[0]["type"] if pre else None
    add("A01", "OK" if first in ("VerifyAPIKey", "OAuthV2") else "FAIL",
        f"first PreFlow policy is {first}" + ("" if first in ("VerifyAPIKey", "OAuthV2") else ": callers are served before they are identified"))
    strip = policy(design, "AssignMessage", "target_request")
    removed = strip and "APIKey" in strip.get("remove_headers", [])
    add("A02", "OK" if removed else "FAIL", "API key removed before the backend" if removed else "API key header is forwarded to S/4HANA")
    q = policy(design, "Quota")
    if not q:
        add("A03", "FAIL", "no Quota policy")
    else:
        add("A03", "OK" if q["identifier"] == "client_id" else "FAIL",
            "quota counts per application" if q["identifier"] == "client_id" else "one quota counter shared by every application")
        add("A04", "OK" if q["limit"] == "product" else "WARN",
            "limit read from the product" if q["limit"] == "product" else f"limit {q['limit']} typed into the policy; product changes won't apply")
    sa = policy(design, "SpikeArrest", "target_request")
    if not sa:
        add("A05", "FAIL", "no Spike Arrest on the target side: nothing protects S4P from bursts")
    else:
        ok = sa["rate_per_s"] <= BACKEND_CAPACITY_PER_S
        add("A05", "OK" if ok else "FAIL", f"Spike Arrest {sa['rate_per_s']}/s against a backend capacity of {BACKEND_CAPACITY_PER_S}/s")
    auth = policy(design, "BasicAuthentication", "target_request")
    kvm = policy(design, "KeyValueMapOperations", "target_request")
    if auth and auth.get("password_source") == "literal":
        add("A06", "FAIL", f"backend password for {auth['user']} written into the policy")
    elif auth and kvm and kvm.get("encrypted"):
        add("A06", "OK", f"backend password read from encrypted map {kvm['map']}")
    else:
        add("A06", "WARN", "backend credential source not clear")
    rf = policy(design, "RowFilter")
    if not rf:
        add("A07", "FAIL", "no filter on the caller's customer")
    else:
        both = set(rf["applies_to"]) >= {"list", "single"}
        add("A07", "OK" if both else "FAIL", "own orders only, on lists and single reads" if both else
            f"customer filter only on {', '.join(rf['applies_to'])} reads: single orders of other customers pass")
    cache = policy(design, "ResponseCache")
    if cache:
        ok = "client_id" in cache["key"] and pre.index(cache) > pre.index(rf) if rf else False
        add("A08", "OK" if ok else "FAIL", "cache key includes the application, cache after the filter" if ok else
            "cache key is the URI only, read before the key check: one caller's answer can reach another")
    else:
        add("A08", "OK", "no response cache")
    wide = [p["name"] for p in design["products"] if "*" in p["resources"] or "*" in p["methods"]]
    add("A09", "FAIL" if wide else "OK", ("products publish every resource and method: " + ", ".join(wide)) if wide else "products publish GET on /A_SalesOrder only")
    base = design["proxy"]["base_path"]
    add("A10", "OK" if base.startswith("/v") else "WARN", f"base path {base}" + ("" if base.startswith("/v") else ": no version, a breaking change has nowhere to go"))
    tgt = design["proxy"]["target"]
    if tgt["kind"] == "api_provider":
        add("A11", "OK", f"target through API provider {tgt['provider']}: {tgt['system_by_stage'][TENANT_STAGE]} in {TENANT_STAGE}")
    else:
        add("A11", "FAIL", f"target URL typed in, pointing at {tgt['system']} from the {TENANT_STAGE} tenant")
    dims = design["statistics"][0]["dimensions"] if design["statistics"] else []
    add("A12", "OK" if "customer" in dims else "WARN", "usage by customer in analytics" if "customer" in dims else "analytics can't show calls per distributor")
    gen = not design["fault"]["return_backend_body"]
    add("A13", "OK" if gen else "WARN", "errors return a short course message" if gen else "backend error bodies are passed to partners")
    untagged = [a["app"] for a in apps if a["product"] == "CAL_Distributor_OrderStatus" and not a["attributes"].get("customer")]
    closed = bool(rf and rf.get("fail_closed"))
    if closed:
        add("A14", "OK", "an application without a customer attribute is refused" + (f" ({', '.join(untagged)} until it has one)" if untagged else ""))
    elif untagged:
        add("A14", "FAIL", f"{', '.join(untagged)} has no customer attribute and would see every order")
    else:
        add("A14", "WARN", "an application without a customer attribute would see every order")
    return rows


# ---------- replay ----------

def replay(design, apps, calls):
    by_key = {a["key"]: a for a in apps}
    products = {p["name"]: p for p in design["products"]}
    counters, cache, last_pass = {}, {}, None
    backend_calls, key_leaks, wrong_rows = 0, 0, 0
    out = []
    tgt = design["proxy"]["target"]
    system = tgt["system_by_stage"][TENANT_STAGE] if tgt["kind"] == "api_provider" else tgt["system"]

    for c in calls:
        app = next((a for a in apps if a["app"] == c["app"]), None)
        headers = {"APIKey": app["key"]} if app else {}
        ctx = {"app": None, "status": None, "body": None, "from_cache": False}
        kind = "list" if c["path"] == "/A_SalesOrder" else "single"
        order = c["path"].split("'")[1] if kind == "single" else None
        cache_pol = None
        for p in design["request_preflow"]:
            if p["type"] == "VerifyAPIKey":
                a = by_key.get(headers.get("APIKey"))
                if not a:
                    ctx["status"], ctx["body"] = 401, "invalid or missing API key"
                    break
                ctx["app"] = a
                prod = products[a["product"]]
                res_ok = "*" in prod["resources"] or any(c["path"].startswith(r) for r in prod["resources"])
                meth_ok = "*" in prod["methods"] or c["method"] in prod["methods"]
                if not (res_ok and meth_ok):
                    ctx["status"], ctx["body"] = 405, f"{c['method']} not in product {prod['name']}"
                    break
            elif p["type"] == "Quota":
                ident = ctx["app"]["app"] if (p["identifier"] == "client_id" and ctx["app"]) else "_shared"
                limit = products[ctx["app"]["product"]]["quota"]["limit"] if p["limit"] == "product" else p["limit"]
                window = (ident, c["t"] // 60)
                counters[window] = counters.get(window, 0) + 1
                if counters[window] > limit:
                    ctx["status"], ctx["body"] = 429, f"quota of {limit} a minute used ({'this app' if ident != '_shared' else 'all apps together'})"
                    break
            elif p["type"] == "RowFilter":
                if ctx["app"] is None:
                    continue
                cust = ctx["app"]["attributes"].get(p["attribute"])
                if not cust and p.get("fail_closed"):
                    ctx["status"], ctx["body"] = 403, "no customer attribute on this application"
                    break
                ctx["filter"] = cust if (cust != "*") else None
                ctx["filter_single"] = "single" in p["applies_to"]
                ctx["filter_list"] = "list" in p["applies_to"]
            elif p["type"] == "ResponseCache":
                cache_pol = p
                key = (c["method"], c["path"]) + ((ctx["app"]["app"],) if "client_id" in p["key"] and ctx["app"] else ())
                hit = cache.get(key)
                if c["method"] == "GET" and hit and c["t"] - hit[0] < p["ttl_s"]:
                    ctx["status"], ctx["body"], ctx["from_cache"] = 200, hit[1], True
                    break
        if ctx["status"] is None:
            # target side
            sa = policy(design, "SpikeArrest", "target_request")
            if sa and last_pass is not None and c["t"] - last_pass < 1.0 / sa["rate_per_s"]:
                ctx["status"], ctx["body"] = 429, "spike arrest"
            else:
                last_pass = c["t"]
                strip = policy(design, "AssignMessage", "target_request")
                if "APIKey" in headers and not (strip and "APIKey" in strip["remove_headers"]):
                    key_leaks += 1
                backend_calls += 1
                filt = ctx.get("filter")
                if c["method"] != "GET":
                    ctx["status"], ctx["body"] = 200, f"order {order} CHANGED in {system}"
                elif kind == "list":
                    rows = [o for o, v in ORDERS.items() if not (filt and ctx.get("filter_list")) or v["SoldToParty"] == filt]
                    ctx["status"], ctx["body"] = 200, "orders " + (",".join(rows) or "(none)")
                else:
                    v = ORDERS.get(order)
                    if v is None or (filt and ctx.get("filter_single") and v["SoldToParty"] != filt):
                        ctx["status"], ctx["body"] = 404, "order not found"
                    else:
                        ctx["status"], ctx["body"] = 200, f"order {order} for {v['CustomerName']}"
                if cache_pol and c["method"] == "GET" and ctx["status"] == 200:
                    key = (c["method"], c["path"]) + ((ctx["app"]["app"],) if "client_id" in cache_pol["key"] and ctx["app"] else ())
                    cache[key] = (c["t"], ctx["body"])
        # did the caller get rows that aren't theirs?
        mine = app["attributes"].get("customer") if app else None
        if ctx["status"] == 200 and app and mine != "*" and ctx["body"].startswith("order"):
            seen = [o for o in ORDERS if o in ctx["body"]]
            if any(ORDERS[o]["SoldToParty"] != mine for o in seen):
                wrong_rows += 1
        out.append((c, ctx))
    return out, backend_calls, key_leaks, wrong_rows, system


def main():
    ap = argparse.ArgumentParser(description="Review and replay a course API proxy design.")
    ap.add_argument("--init", action="store_true", help="write the designs and traffic to unit26/apim/")
    ap.add_argument("action", nargs="?", choices=["review", "replay"])
    ap.add_argument("design", nargs="?", choices=["draft", "reviewed"])
    args = ap.parse_args()

    if args.init:
        HERE.mkdir(parents=True, exist_ok=True)
        for d in (DRAFT, REVIEWED):
            (HERE / f"proxy_{d['name']}.json").write_text(json.dumps(d, indent=2) + "\n", encoding="utf-8")
        (HERE / "apps.json").write_text(json.dumps(APPS, indent=2) + "\n", encoding="utf-8")
        (HERE / "traffic.json").write_text(json.dumps(traffic(), indent=2) + "\n", encoding="utf-8")
        print(f"Wrote proxy_draft.json, proxy_reviewed.json, apps.json, traffic.json to {HERE}")
        return 0
    if not args.action or not args.design:
        ap.error("give an action and a design, for example: review draft (run --init first)")
    path = HERE / f"proxy_{args.design}.json"
    if not path.exists():
        print(f"{path} not found. Run: python unit26/apim_review.py --init")
        return 1
    design = json.loads(path.read_text(encoding="utf-8"))
    apps = json.loads((HERE / "apps.json").read_text(encoding="utf-8"))
    calls = json.loads((HERE / "traffic.json").read_text(encoding="utf-8"))

    if args.action == "review":
        rows = review(design, apps)
        for rule, status, text in rows:
            print(f"{rule}  {status:<4}  {text}")
        n = {s: sum(1 for r in rows if r[1] == s) for s in ("OK", "WARN", "FAIL")}
        print(f"{len(rows)} checks: {n['OK']} OK, {n['WARN']} WARN, {n['FAIL']} FAIL")
        return 2 if n["FAIL"] else 0

    out, backend, leaks, wrong, system = replay(design, apps, calls)
    shown = set()
    for c, ctx in out:
        if c["note"] == "Hallam's retry loop":
            # print the loop compactly: first call and every change of outcome
            sig = (ctx["status"], ctx["from_cache"])
            if sig in shown:
                continue
            shown.add(sig)
        app = c["app"] or "(none)"
        src = " (cache)" if ctx["from_cache"] else ""
        print(f"{c['id']}  {app:<10}  {c['method']:<5} {c['path'].split('?')[0]:<24} {ctx['status']}{src}  {ctx['body']}")
    statuses = [ctx["status"] for _, ctx in out]
    crm = next((ctx for c, ctx in out if c["id"] == "T32"), {"status": "-"})
    print(f"{len(out)} calls: {statuses.count(200)} answered, {statuses.count(429)} refused 429, "
          f"{sum(1 for s in statuses if s in (401, 403, 404, 405))} refused 401/403/404/405")
    print(f"Backend {system}: {backend} calls, API key seen {leaks} times; "
          f"answers with another customer's orders: {wrong}; CRM call T32: {crm['status']}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

#### Step 3: Write the designs and the traffic

1. Run:

   ```bash
   python unit26/apim_review.py --init
   ```

2. You see one line ending with your own path:

   ```text
   Wrote proxy_draft.json, proxy_reviewed.json, apps.json, traffic.json to .../orchestrate-course/unit26/apim
   ```

3. Open `unit26/apim/proxy_draft.json`. It is the partner's draft: the cache first, a quota of 20 with no identifier, a customer filter on lists only, a password written into the backend step, the test system's address typed in, and products that publish every resource and method.

> **Warning** `--init` overwrites the four files. Run it once, or again only when you want to start over.

#### Step 4: Review the draft

1. Run:

   ```bash
   python unit26/apim_review.py review draft
   ```

2. You should see:

   ```text
   A01  FAIL  first PreFlow policy is ResponseCache: callers are served before they are identified
   A02  FAIL  API key header is forwarded to S/4HANA
   A03  FAIL  one quota counter shared by every application
   A04  WARN  limit 20 typed into the policy; product changes won't apply
   A05  FAIL  no Spike Arrest on the target side: nothing protects S4P from bursts
   A06  FAIL  backend password for TU_APIM_ORDERS written into the policy
   A07  FAIL  customer filter only on list reads: single orders of other customers pass
   A08  FAIL  cache key is the URI only, read before the key check: one caller's answer can reach another
   A09  FAIL  products publish every resource and method: CAL_Distributor_OrderStatus, CAL_Internal_OrderStatus
   A10  WARN  base path /salesorderstatus: no version, a breaking change has nowhere to go
   A11  FAIL  target URL typed in, pointing at S4Q from the prod tenant
   A12  WARN  analytics can't show calls per distributor
   A13  WARN  backend error bodies are passed to partners
   A14  WARN  an application without a customer attribute would see every order
   14 checks: 0 OK, 5 WARN, 9 FAIL
   ```

The command ends with exit code 2 because there is at least one FAIL, so a pipeline would stop here.

#### Step 5: Replay the draft

1. Run:

   ```bash
   python unit26/apim_review.py replay draft
   ```

2. You should see (Hallam's 25-call retry loop is printed once per new outcome):

   ```text
   T01  HFS-ORDERS  GET   /A_SalesOrder('1000002') 200  order 1000002 for Hallam Fluid Systems
   T02  (none)      GET   /A_SalesOrder('1000002') 200 (cache)  order 1000002 for Hallam Fluid Systems
   T03  HFS-ORDERS  GET   /A_SalesOrder            200  orders 1000002,1000005
   T04  BWU-PORTAL  GET   /A_SalesOrder            200 (cache)  orders 1000002,1000005
   T05  HFS-ORDERS  GET   /A_SalesOrder('1000003') 200  order 1000003 for Brennock Water Utility
   T06  HFS-ORDERS  PATCH /A_SalesOrder('1000002') 200  order 1000002 CHANGED in S4Q
   T07  HFS-ORDERS  GET   /A_SalesOrder('1000005') 200  order 1000005 for Hallam Fluid Systems
   T23  HFS-ORDERS  GET   /A_SalesOrder('1000005') 429  quota of 20 a minute used (all apps together)
   T32  CRM-CPUS    GET   /A_SalesOrder('1000004') 429  quota of 20 a minute used (all apps together)
   T33  BWU-PORTAL  GET   /A_SalesOrder('1000007') 200  order 1000007 for Brennock Water Utility
   33 calls: 23 answered, 10 refused 429, 0 refused 401/403/404/405
   Backend S4Q: 21 calls, API key seen 21 times; answers with another customer's orders: 2; CRM call T32: 429
   ```

Read it as a review board would. A call without a key got an order (T02). Brennock got Hallam's list from the cache (T04). Hallam read Brennock's order (T05) and changed an order (T06). Hallam's loop used up everyone's quota, so Calder's CRM was refused (T32). And everything went to the test system `S4Q`.

#### Step 6: Review the reviewed design

1. Run:

   ```bash
   python unit26/apim_review.py review reviewed
   ```

2. The last lines read:

   ```text
   A13  OK    errors return a short course message
   A14  WARN  an application without a customer attribute would see every order
   14 checks: 13 OK, 1 WARN, 0 FAIL
   ```

The one WARN is real: if an admin forgets the customer number on a new application, the filter has nothing to filter by. The exercise fixes it.

#### Step 7: Replay the reviewed design

1. Run:

   ```bash
   python unit26/apim_review.py replay reviewed
   ```

2. You should see:

   ```text
   T01  HFS-ORDERS  GET   /A_SalesOrder('1000002') 200  order 1000002 for Hallam Fluid Systems
   T02  (none)      GET   /A_SalesOrder('1000002') 401  invalid or missing API key
   T03  HFS-ORDERS  GET   /A_SalesOrder            200  orders 1000002,1000005
   T04  BWU-PORTAL  GET   /A_SalesOrder            200  orders 1000003,1000004,1000006,1000007
   T05  HFS-ORDERS  GET   /A_SalesOrder('1000003') 404  order not found
   T06  HFS-ORDERS  PATCH /A_SalesOrder('1000002') 405  PATCH not in product CAL_Distributor_OrderStatus
   T07  HFS-ORDERS  GET   /A_SalesOrder('1000005') 200  order 1000005 for Hallam Fluid Systems
   T24  HFS-ORDERS  GET   /A_SalesOrder('1000005') 429  quota of 20 a minute used (this app)
   T32  CRM-CPUS    GET   /A_SalesOrder('1000004') 200  order 1000004 for Brennock Water Utility
   T33  BWU-PORTAL  GET   /A_SalesOrder('1000007') 200  order 1000007 for Brennock Water Utility
   33 calls: 22 answered, 8 refused 429, 3 refused 401/403/404/405
   Backend S4P: 23 calls, API key seen 0 times; answers with another customer's orders: 0; CRM call T32: 200
   ```

Hallam's own loop is stopped after its 20th call in the minute, and nobody else notices. Hallam gets `404` for Brennock's order rather than `403`, so it can't even learn that the order exists.

> **Note** These results come from a made-up model of a proxy and 33 made-up calls. They show the method of a design review, not the behavior of a real SAP tenant.

#### Step 8: Save your work in Git

```bash
git add unit26/apim_review.py unit26/apim
git commit -m "Unit 26: API proxy review and replay for I14"
```

#### How the code works

| Part | What it does |
| --- | --- |
| `ORDERS` | Six open orders from the order-to-cash topic, as the stand-in S/4HANA API would return them |
| `APPS` | Three applications: Hallam's and Brennock's systems on the distributor product, Calder's CRM on the internal one; each carries a `customer` attribute (`*` for the CRM) |
| `DRAFT`, `REVIEWED` | Two designs in a course JSON format: PreFlow policies in order, target-side policies, products, statistics and fault handling. Policy names follow SAP's classic types; `RowFilter` stands for the logic you would build from the application's attribute |
| `traffic()` | 33 calls in the first minute plus one a minute later; the loop adds a timestamp to each call, as many retry bugs do, so the cache can't absorb it |
| `review()` | Rules `A01`-`A14`: order, scope and presence of each policy, products, version, provider, analytics, error bodies and untagged applications |
| `replay()` | Runs each call through the policies in their order, then the target side, counting backend calls, leaked keys and answers with other customers' orders |

Two simplifications to know: SAP's Response Cache is attached in both the PreFlow and the PostFlow, which the model folds into one step, and the model treats a quota window as one clock minute.

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python` is not recognized / command not found | Python isn't on the path, or the virtual environment isn't on | Turn on `.venv` (Step 1); on macOS or Linux try `python3` |
| `proxy_draft.json not found` | You skipped `--init` | Run `python unit26/apim_review.py --init` |
| `json.decoder.JSONDecodeError` | A comma or quote is missing after an edit | Undo the edit, or run `--init` to start over |
| `KeyError` on a product name | An application names a product that isn't in the design | Use `CAL_Distributor_OrderStatus` or `CAL_Internal_OrderStatus` |
| Output differs from the samples | A file was edited, or the script differs | Run `--init` again and compare the script with the one above |
| Network or proxy errors | Not from this script: it uses no network | Look at the command you ran; this lab needs none |

### The SAP way

What SAP provides for this work, as of 29 November 2026:

- **API Management in SAP Integration Suite**, with the API portal for classic proxies, Integration Suite's design area for API artifacts, Developer Hub and API analytics ([SAP](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/api-management-de3fea6.md)). Runtimes and features depend on the service plan (SAP Note 2903776).
- **Classic proxies** built from an API provider, a URL, an existing proxy, an OpenAPI description or the API designer, with the policy designer, **policy templates** for reuse, debugging, revisions and versions.
- **API artifacts on Integration Cell** (generally available since 5 July 2026) with mandatory Authentication, Authorization by scope or developer key, Quota, Surge Protection, IP Filter, validation and threat protection, plus mediation steps and reusable API artifacts.
- **Developer Hub governance**: approval of registrations, product visibility by role collection, and product permissions for discovery and subscription ([Governance](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/governance-fac716e.md)). Admin roles include `APIPortal.Administrator` in the API portal and `AuthGroup.API.Admin` in Developer Hub.
- **Transport** of proxies, products, providers, maps and certificates with SAP Cloud Transport Management ([SAP](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/transport-api-management-artifacts-via-sap-cloud-transport-management-service-2e4bc72.md)).
- **Rate plans and billing** in Developer Hub for teams that charge for APIs. Calder doesn't.
- **Licensing note.** Check how your edition counts API calls and which runtimes it includes on the [pricing page](https://www.sap.com/products/technology-platform/integration-suite/pricing.html) before sizing partner traffic.

### Build vs. SAP

| Need | SAP feature | Custom or lab approach | Use which |
| --- | --- | --- | --- |
| Identify partners | Verify API Key or OAuth; Authentication on Integration Cell | Keys checked in your own app | SAP's: keys and tokens issued and revoked in one place |
| Per-customer data scope | Application custom attributes read at runtime; principal propagation to S/4HANA | Filter in a custom backend service | Gateway filter plus a backend check where the user is propagated; never only the partner's own filter |
| Limit consumers | Quota with an identifier | Counting in the backend | SAP's, per application |
| Protect S/4HANA | Spike Arrest or Surge Protection | Bigger S/4HANA sizing | SAP's, sized to measured capacity |
| Review designs | Policy templates, debugging | `apim_review.py` with Calder's rules | Both: templates make the right design easy, the pipeline check stops the wrong one |
| Publish to partners | Developer Hub with approval and product permissions | A wiki page and keys by email | Developer Hub |

### Architecture view

**Where it sits.** `I14` runs in API Management of the `calder-int-prod` subaccount. Hallam's and Brennock's systems call over the internet; Calder's CRM calls from its own network. The proxy reaches `CP10`'s production system `S4P` through the API provider `S4_ORDERS`, which uses the Cloud Connector pair `SCC-RK-P` and virtual host `s4p-api:443`, as in the [connectivity topic](https://erpfde.com/topics/btp-connectivity/). The diagram under *How it works* shows the chain.

**Non-functional requirements.**

| Requirement | Target for `I14` | What breaks if missed |
| --- | --- | --- |
| Data scope | Every answer limited to the caller's customer | Confidentiality breach between customers |
| Consumer limit | 20 calls a minute per distributor application, 600 for the CRM (course values) | One partner's bug blocks the rest |
| Backend protection | Spike Arrest at 8 a second against a measured 10 a second (course values) | S/4HANA slows for internal users too |
| Latency | Order status within 2 seconds, cached reads for 60 seconds | Partners poll harder, adding load |
| Availability | Same as `S4P`'s window; analytics alert on error rate | Partners phone customer service instead |
| Audit | Calls per application and customer in analytics, kept 6 months | Nobody can say who read what |

**Integration and identity.** Each distributor's system is an application with its own key and a `customer` attribute set by Calder's admin, not by the partner. The proxy removes the key before calling S/4HANA and signs in with technical user `TU_APIM_ORDERS`, whose role only reads sales orders in sales org `CPUS`; its password is in an encrypted key value map. Because that user can read every customer's orders, **the gateway filter is the only line between customers** in this design, which is why rules A07, A08 and A14 matter. The released API behind it is the sales order API; [calling your first SAP API](https://erpfde.com/topics/calling-your-first-sap-api/) shows how to read its description.

**The decision to record** (short ADR form from the [design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/)):

- **Context.** `I14` is Calder's first partner API. Agents may use it later, and SAP's MCP gateway builds an MCP server from an API artifact only when the artifact runs on Integration Cell with OAuth.
- **Options.** A: classic proxy with API keys and the reviewed policy chain. B: API artifact on Integration Cell with OAuth client credentials per distributor, Authorization by developer key, Quota per client ID and Surge Protection. C: API artifact on Edge Integration Cell at Rockford.
- **Decision.** B, if a two-week pilot shows the artifact can apply the per-customer filter from the client ID; otherwise A, with B planned before agents use the API. C is rejected: partner traffic comes from the internet, and nothing requires running the gateway at the plant.
- **Consequences.** Distributors move from keys to OAuth tokens, which their teams must support. Calder's rules A01-A14 are restated in the artifact's terms (Authentication instead of Verify API Key, Surge Protection instead of Spike Arrest). The service plan and region must include Integration Cell.

**What a design review will ask.**

1. Show me Hallam asking for Brennock's order, and what it gets back.
2. What happens to the CRM when one distributor's system loops?
3. Who sets a distributor's customer number on its application, and what happens if they forget?
4. Which system does production call, and where is that set?
5. When we rename a field, how do partners find out, and how long does the old version run?

### Production concerns

- **Security and SAP authorizations.** Keep the backend user's role to reads in `CPUS`; a gateway filter doesn't replace S/4HANA authorizations, it narrows them. Where users, not systems, call, prefer principal propagation so S/4HANA checks the person. Store credentials in encrypted maps or the provider, rotate them, and remove keys and tokens from headers before the backend and from logs. Limit `APIPortal.Administrator`: an admin can see application keys and secrets.
- **Evaluation.** Keep the 33 calls, add a call for every incident and every new partner, and run review and replay in the pipeline before each transport. A FAIL stops the import.
- **Cost.** Check how your edition meters API calls; caching per application cuts backend load but not gateway calls. Check SAP's limits too: products with more than 100 resources may time out, and SAP advises 20 to 30 products per application at most.
- **Operations.** Watch 429s per application (a partner bug or a quota that is too low), 5xx from the backend, and certificate expiry. SAP lets you monitor API Management certificates in SAP Cloud ALM. Remove applications when partners leave.
- **Clean core.** Point proxies only at released APIs. A proxy over a custom service carries that service's upgrade risk to every partner, as the [clean core topic](https://erpfde.com/topics/integration-platform-and-clean-core/) explains.

### Where AI fits

As of November 2026, AI touches API Management in three ways:

- **Agents become consumers.** An agent calling S/4HANA is one more application, with the same need for identity, quotas and data scope. SAP's MCP gateway exposes API artifacts as MCP tools; the [MCP gateway topic](https://erpfde.com/topics/integration-suite-mcp-gateway-hands-on/) builds one, and the [AI gateways topic](https://erpfde.com/topics/ai-gateways-for-model-and-agent-traffic/) covers model and agent traffic. Since 20 September 2026 SAP also lists an **LLM proxy** API artifact with an OpenAI-compatible interface for model calls ([what's new](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/what-s-new-for-sap-api-management-cloud-foundry-d9d60be.md)).
- **AI in the tool.** SAP lists AI-assisted OpenAPI generation (April 2026), an AI assistant for API analytics (July 2026) and anomaly detection on API traffic. SAP's [anomaly detection page](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/anomaly-detection-7a4fe7d.md) says these AI features are in the Premium and Enhanced editions, as a free promotion until the January 2027 release; anomaly detection also needs at least three months of API history.
- **AI-drafted proxies.** A proxy or OpenAPI description drafted by AI goes through the same review. The rules check what the design does, not who wrote it.

### Pitfalls

- **The cache first.** A Response Cache before the key check answers anyone who repeats a cached address.
- **One counter for everyone.** A Quota without an identifier is shared by every application.
- **Quota as backend protection.** It counts over a period; bursts still hit S/4HANA. Use Spike Arrest or Surge Protection.
- **Spike Arrest per client.** SAP advises against it: it isn't distributed and smooths per server.
- **A product quota with no policy.** The product's number does nothing until Verify API Key and Quota are on the API.
- **Filtering lists but not single reads.** Partners guess order numbers.
- **The whole service in the product.** Write operations reach partners nobody meant to give them.
- **Treating the Deprecated state as a switch.** SAP says states are for demarcation only; plan the shutdown of an old version yourself.
- **Typed-in backend addresses.** The API provider exists so each tenant can point to its own system.

### Exercise

Calder onboards two more distributors: Pellmark Industrial Supply (customer `10000031`) and Ostervale Municipal Water (`10000021`). The admin forgets Ostervale's customer number. Find it with the review, then make the proxy refuse untagged applications.

1. Open `unit26/apim/apps.json`. Before the closing `]`, add a comma after the last entry and these two entries:

   ```json
   {"app": "PIS-ORDERS", "developer": "Pellmark purchasing", "key": "calder-lab-key-pis", "product": "CAL_Distributor_OrderStatus", "attributes": {"customer": "10000031"}},
   {"app": "OST-ORDERS", "developer": "Ostervale IT", "key": "calder-lab-key-ost", "product": "CAL_Distributor_OrderStatus", "attributes": {}}
   ```

2. Open `unit26/apim/traffic.json` and add two calls at the end the same way:

   ```json
   {"id": "T34", "t": 75, "app": "PIS-ORDERS", "method": "GET", "path": "/A_SalesOrder", "note": "Pellmark lists its orders"},
   {"id": "T35", "t": 76, "app": "OST-ORDERS", "method": "GET", "path": "/A_SalesOrder", "note": "Ostervale lists its orders"}
   ```

3. Run `python unit26/apim_review.py review reviewed`. A14 now reads `FAIL  OST-ORDERS has no customer attribute and would see every order`.
4. Run `python unit26/apim_review.py replay reviewed`. T34 shows `orders (none)`: Pellmark has no open orders, which is a correct empty answer. T35 shows all six orders: the leak.
5. In `unit26/apim/proxy_reviewed.json`, find the `RowFilter` policy and change `"fail_closed": false` to `"fail_closed": true`.
6. Review again: `14 checks: 14 OK, 0 WARN, 0 FAIL`. Replay: T35 reads `403  no customer attribute on this application`.
7. Set Ostervale's attribute to `{"customer": "10000021"}` and replay. T35 now reads `200  orders (none)`.
8. Write one line in your review notes: who sets the customer attribute when a distributor is onboarded, and who checks it.

**Done when:** the review prints `14 checks: 14 OK, 0 WARN, 0 FAIL`, the replay shows T35 refused with `403` before the attribute is set and answered with `orders (none)` after, and your notes name the owner. The reviewed design and calls feed the [integration security topic](https://erpfde.com/topics/integration-security/).

> **Note** These results come from made-up applications and calls, not from a real SAP tenant.

### Check yourself

1. In the draft, a call without any key got an order back. Why?
   - A. Verify API Key was disabled with continueOnError set to true
   - B. The Response Cache ran before Verify API Key in the PreFlow
   - C. The product published every resource and every method
   - D. Spike Arrest was missing on the target side of the proxy

   Answer: B. Policies run in the order attached. A cache placed before the key check answers anyone who repeats a cached address, so identity must come first and the cache after the filter.

2. What does a Quota policy with no Identifier count, according to SAP?
   - A. One counter per application, taken from the API key
   - B. One counter per API product the application subscribes to
   - C. One counter per policy name, shared by all callers
   - D. One counter per backend system behind the API provider

   Answer: C. By default a Quota policy keeps a single counter based on its name. The Identifier element gives separate counters per app or client, which keeps one partner's loop inside its own limit.

3. Brennock received Hallam's order list from the cache. Which fix addresses the cause?
   - A. Shorten the cache time from 300 to 60 seconds
   - B. Exclude error responses from the cache
   - C. Add the application to the cache key and cache after the filter
   - D. Move the cache from the PreFlow to the PostClientFlow

   Answer: C. SAP builds the cache key from key fragments you choose, and that key decides which requests share an answer. A shorter time only narrows the window; the application in the key closes it.

4. Where should the backend password for TU_APIM_ORDERS live?
   - A. In the Basic Authentication policy, so each proxy has its own copy
   - B. In an encrypted key value map read by the proxy at runtime
   - C. In a custom attribute on the CRM's application in Developer Hub
   - D. In the proxy's base path, so it changes with each version

   Answer: B. A password typed into a policy travels with every export and transport. The reviewed design reads it from an encrypted key value map, as SAP's map supports encrypted values.

5. The team wants to rename a field in the order status response. What should they create?
   - A. A new revision, so partners keep the same address
   - B. A new product, so partners subscribe again
   - C. A Deprecated state on the proxy, which stops old calls
   - D. A new version with the version in the base path

   Answer: D. Renaming a field is incompatible. SAP describes versions for such changes, with the version in the URL and several versions running side by side; revisions are for compatible changes, and states don't stop calls.

6. A new distributor's application has no customer attribute. What should the reviewed proxy do?
   - A. Refuse its calls until the admin sets the customer number
   - B. Return all orders, since the key itself is valid
   - C. Return the CRM's view, since that is the internal default
   - D. Let S/4HANA decide, since the backend user checks customers

   Answer: A. The backend user can read every customer's orders, so the gateway filter is the only line between customers. Failing closed turns a forgotten attribute into a refused call instead of a leak.

7. Calder wants agents to use I14 later through SAP's MCP gateway. What does that imply for the runtime choice?
   - A. Classic API proxies with API keys can be turned into MCP servers directly
   - B. The runtime doesn't matter, since agents call S/4HANA directly
   - C. It favors an API artifact on Integration Cell secured with OAuth
   - D. It requires Edge Integration Cell at Rockford for every agent call

   Answer: C. To build an MCP server from an API artifact, SAP requires the artifact on Integration Cell with OAuth-based authentication. Choosing that runtime for I14 now keeps the agent path open.

8. Hallam's retry loop sends 25 calls in 25 seconds. In the reviewed design, what protects S/4HANA and what protects the other partners?
   - A. Spike Arrest protects the other partners and Quota protects S/4HANA
   - B. Spike Arrest protects S/4HANA and the per-app Quota protects the partners
   - C. The Response Cache protects both, since the loop repeats one address
   - D. Developer Hub protects both, since it can approve each Hallam call

   Answer: B. SAP says to set Spike Arrest to what the backend can handle and not to use it per client, while a Quota with an identifier caps each application. The loop's timestamps also defeat the cache.

## Sources

- [API Management (SAP Integration Suite documentation, SAP-docs on GitHub, read 2026-11-29)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/api-management-de3fea6.md): three runtimes (Classic API Management, Integration Cell, Edge Integration Cell); Integration Studio for design, Developer Hub as the portal; shared platform services
- [API-Centric Integration (SAP Integration Suite documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/ISuite_Integrations_APIs/api-centric-integration-cf4b847.md): API artifacts that combine security, traffic management and integration steps; when to use simple governed APIs instead
- [Flow (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/flow-08b40d9.md): request and response pipelines on proxy and target endpoints; PreFlow, conditional flows (first match only), PostFlow, PostClientFlow; quota and security policies in the proxy PreFlow
- [Policy Types (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/policy-types-c918e28.md): enabled, continueOnError and async attributes; list of prebuilt policies (Verify API Key, OAuth v2.0, Quota, Spike Arrest, Assign Message, Key Value Map Operations, Response Cache, Statistics Collector, threat protection and others)
- [Understanding Quota Counters (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/understanding-quota-counters-cb606e3.md): one counter per policy name by default; Identifier for counters per app or client; counters scoped to the API proxy
- [Spike Arrest (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/spike-arrest-bf441dc.md): a rate, not a count; 6 per minute means one every 10 seconds; not distributed; throttle to what the backend can handle, not per client
- [Response Cache (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/response-cache-8df3fac.md): attached in PreFlow and PostFlow; 512 KB per object; caches error responses unless excluded; CacheKey with KeyFragment builds the namespace that matches requests to cached responses
- [API Revisions (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/api-revisions-58097ac.md): revisions for compatible changes with the same URL, one in the runtime; versions for incompatible changes with the version in the URL, several in the runtime
- [Custom Attributes (SAP API Management documentation)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/custom-attributes-90a5a6d.md): attributes on products and on applications created by an admin; read at runtime through Verify API Key, access token and Access Entity policies; limits 18 attributes, 255 and 1024 characters
- [What's New for SAP API Management Cloud Foundry (SAP-docs on GitHub)](https://github.com/SAP-docs/btp-integration-suite/blob/main/docs/apim/API-Management/what-s-new-for-sap-api-management-cloud-foundry-d9d60be.md): API-centric integration, reusable API artifacts and MCP gateway GA 2026-07-05; AI assistant in analytics 2026-07-26; LLM proxy 2026-09-20; principal propagation for on-premise API artifacts 2026-10-18; quota identifier defaults to the client ID 2026-05-31
