Sub topic 11
Consuming queries outside the launchpad
This chapter assumes you can build a cube, a dimension and a query view with @Analytics.query: true, as in the earlier chapters. It also assumes you know basic HTTP and what a REST or OData call looks like. The Fiori launchpad is only one client of an analytical query. Excel, SAP Analytics Cloud, a data warehouse and your own scripts can read the same query, and each one has different rules for authentication, shape and volume.
One query, several doors
The analytical query is defined once in the consumption layer. Clients reach it through different protocols, and every path ends at the same CDS view and the same access control.
The table compares the four options.
| Consumer | Protocol | Typical use | Data volume |
|---|---|---|---|
| Script, Power BI, Excel | OData (V2 or V4) | Custom apps, small reports | Small to medium |
| SAP Analytics Cloud | Live connection (InA) | Dashboards on live data | Aggregated results |
| Analysis for Office | InA | Ad hoc pivoting in Excel | Aggregated results |
| Warehouse or lake | Extraction (ODP, CDS extraction) | Replicating data | Large, often delta |
The sections below cover each option, starting with the common prerequisite for all of them.
What must be true before any external call works
A query view that works in a Fiori app can still fail for an external client. Check these items first.
- The view must be a query (
@Analytics.query: true) or, for extraction, a cube or dimension with extraction enabled. A plain interface view does not give an external client the analytical behavior. - The user that the client connects with needs the right authorizations. This means the authorization object for the service, and the data authorizations your DCL role checks.
- The service must be active on the front-end server, or in an SAP BTP ABAP environment, the service binding must be published.
- The client must be able to reach the system. This is a network and certificate matter, often involving SAP Cloud Connector or a reverse proxy.
The DCL role you wrote for the query applies to every consumer. An external client has no way to skip the row-level restrictions. The result for a given user is the same whether they use a Fiori tile or a script.
Exposing a query as an OData service
The simplest way for a classic on-premise system is the @OData.publish annotation. It generates an OData V2 service from the view. Here is the query from the earlier chapter, with Currency added and the annotation set.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Net amount by customer'
@Analytics.query: true
@OData.publish: true
define view entity ZC_NetAmountByCustomer
as select from ZI_SalesItemCube
{
@AnalyticsDetails.query.axis: #ROWS
CustomerId,
@AnalyticsDetails.query.axis: #ROWS
Currency,
@AnalyticsDetails.query.axis: #COLUMNS
NetAmount
}Currency belongs in the select list because an amount without its currency cannot be aggregated safely. Without it the analytical engine cannot know whether rows with different currencies may be summed.
The generated service name is the view name in upper case with the suffix _CDS, for example ZC_NETAMOUNTBYCUSTOMER_CDS. You then activate it in transaction /IWFND/MAINT_SERVICE, which registers it in the gateway.
Newer releases and the ABAP environment on SAP BTP prefer an explicit approach. You create a service definition that exposes the query, then a service binding of an OData type such as V4 Web API. Binding types and the exact support for analytical queries differ between releases. Check the ADT dialog and the SAP Help documentation for your release before you choose.
<br>
What the service looks like to a client
An analytical OData service behaves differently from a plain entity list. Three points matter.
- The service returns aggregated rows. The dimensions you request in
$selectdefine the grouping level, and the measures are summed per group. Selecting fewer dimensions gives fewer, more aggregated rows. - Measures need their unit or currency selected too. Request
Currencytogether withNetAmount. - Filters on dimensions use
$filterand are applied before aggregation, so$filter=Country eq 'DE'limits the data that is summed.
The entity set name is not always the view name. For a query without parameters it is often the view name, and for a query with parameters it usually has a Results suffix plus a separate parameters entity. Read $metadata to see the actual names instead of guessing.
Calling it from a script
The following Python script reads the service. It takes the host, service path, entity set and credentials from the environment, and it follows server-side paging.
import os
import requests
BASE = os.environ["S4_BASE_URL"] # e.g. https://s4host:44300
SERVICE = os.environ.get("S4_SERVICE", "/sap/opu/odata/sap/ZC_NETAMOUNTBYCUSTOMER_CDS")
ENTITY_SET = os.environ.get("S4_ENTITY_SET", "ZC_NetAmountByCustomer")
AUTH = (os.environ["S4_USER"], os.environ["S4_PASSWORD"])
def fetch_all():
url = f"{BASE}{SERVICE}/{ENTITY_SET}"
params = {
"$select": "CustomerId,Currency,NetAmount",
"$format": "json",
"$top": "1000",
}
rows = []
with requests.Session() as session:
session.auth = AUTH
session.headers["Accept"] = "application/json"
while url:
response = session.get(url, params=params, timeout=60)
response.raise_for_status()
payload = response.json()["d"]
rows.extend(payload["results"])
url = payload.get("__next") # server-driven paging link
params = None # the next link already carries the query
return rows
if __name__ == "__main__":
for row in fetch_all():
print(row["CustomerId"], row["NetAmount"], row["Currency"])The script sets params to None after the first call. The __next link already contains the query options, and sending them twice produces errors or duplicate options.
<br>
Live connections: SAP Analytics Cloud and Analysis for Office
SAP Analytics Cloud (SAC) and Analysis for Office do not read your query through OData. They use the InA (Information Access) protocol of the analytical engine, which supports navigation, hierarchies, variables and drill-down. These features are richer than a flat OData response.
For a CDS query, the system registers a technical query name. The name is the view name with the prefix 2C, for example 2CZC_NetAmountByCustomer, which is the name you pick in the client's connection dialog. A live connection in SAC to an S/4HANA system requires these elements:
- the InA service active on the S/4HANA system,
- a connection definition in SAC, typically through a Cloud Connector to reach an on-premise system,
- a user who exists in both worlds, commonly through single sign-on, so the same DCL role applies.
Because the connection is live, SAC stores no copy of the data. Each chart refresh runs the query on the S/4HANA database. Slow queries therefore show up as slow dashboards, and many users opening one dashboard at once add load to the transactional system. The performance chapter covers how to model for that case.
Extracting data instead of querying it
Sometimes the consumer should own a copy, for example a central data warehouse that joins S/4HANA data with other sources. The right tool then is extraction, not a query. You mark the cube or dimension as extraction-enabled:
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Sales item cube'
@Analytics.dataCategory: #CUBE
@Analytics.dataExtraction.enabled: true
define view entity ZI_SalesItemCube
as select from zsales_item
{
key item_uuid as ItemUuid,
customer_id as CustomerId,
currency as Currency,
@DefaultAggregation: #SUM
@Semantics.amount.currencyCode: 'Currency'
net_amount as NetAmount
}With this annotation the view becomes available through the Operational Data Provisioning (ODP) framework, and the extraction tool of the target system, such as SAP BW/4HANA or SAP Datasphere, can read it. For large tables, extraction supports full loads and, when the view declares a change-data-capture setup, delta loads. Without delta support, every load transfers the entire table.
Extraction reads at the granularity of the cube, not the aggregated query result. It also differs in authorizations. Extraction commonly runs under a technical user and often has no per-user restrictions. Decide deliberately who may see the replicated copy, because DCL row-level filters no longer protect it once the rows leave the system.
Choosing a path
| Question | Prefer |
|---|---|
| A custom app or script needs a few thousand aggregated rows | OData service |
| Business users want dashboards on live numbers | SAC live connection |
| Analysts want to pivot in Excel with hierarchies | Analysis for Office |
| Data must be combined with other sources, or history kept | Extraction to a warehouse |
| Query results exceed hundreds of thousands of rows | Extraction, not OData |
Common errors
- 404 on the service URL. The service is not activated in the gateway, or the entity set name differs from what you assumed. Open
$metadataand copy the names. - 401 or 403. The user lacks the service authorization or the logon is rejected. A technical user for scripts still needs the business catalog or role that includes the service.
- Empty result although data exists. The DCL role grants the user no rows. Test the same query in the Fiori app or the ADT data preview with that user.
- Amounts without currency, or an error about unit and currency.
Currencyis missing from$selector from the query's select list. - Timeouts on large result sets. The call asks for too many rows or too fine a grain. Add
$filterconditions, select fewer dimensions, or switch to extraction. - Query not found in SAC or Analysis for Office. Look for the
2Cprefixed name. Also check that the view is marked@Analytics.query: trueand that the InA service is active.
Exercise
A colleague reads your analytical query through OData and gets the same total for every customer, although they selected only NetAmount in $select. What is the likely cause, and how do you fix it?
Show answer
Without a dimension in $select, the service aggregates all rows into one group, so every request returns the grand total. Add CustomerId (and Currency, so the amount can be aggregated safely) to $select. The dimensions in $select define the grouping level.
Exercise
Your team must feed a central warehouse with 40 million sales items every night. A developer proposes calling the OData service of ZC_NetAmountByCustomer in a loop. Which approach would you choose instead, and which security aspect must you review afterwards?
Show answer
Enable extraction on the cube (@Analytics.dataExtraction.enabled: true) and load it through ODP, using delta loads where the view supports them. OData is meant for aggregated, moderate result sets. Afterwards, review authorizations: extraction usually runs under a technical user, so the DCL row-level restrictions do not protect the copy in the warehouse, and access there must be controlled separately.