Beyond ABAPdesigned by@Tejoram97
Beyond ABAP / CAP / Services & Generic Providers – OData, REST & Projections

Services & Generic Providers – OData, REST & Projections

CAP · SAP BTP ·

Open the interactive lesson →
  1. Why services: one model, many APIs
  2. Service definitions and projections
  3. Protocols and endpoints: OData V4, REST and more
  4. Generic providers: served out of the box
  5. Generic input validation
  6. Trying a service: index page, .http files, curl
  7. Interview questions

How the Order Approval Portal exposes its model (CR2): service definitions and projections, auto-exposure and redirection, protocols and endpoints (OData V4, REST, OData V2 adapter, GraphQL), everything generic providers serve without code, generic input validation, and how to call the services locally.

Part 1 – Why services: one model, many APIs

Requirements on this page

CR-ID

Requirement

Where on the page

CR2

Reps and managers get different APIs on the same data

Part 1 (idea), Part 2 (projections), Part 3 (protocols and endpoints)

CR2

No code for standard reads and writes

Part 4 (generic providers)

CR3 (declarative part)

Reject bad input, e.g. a rejection without a reason

Part 5 (annotations); coded checks on 04 · Custom Logic in Node.js

The domain model (02 · CDS Modeling) says what exists. A service says who may see and do what, through which API. Reps need to create requests and add notes for their region; managers need a slimmer view of open requests plus Approve / Reject. Instead of one big API with if-statements, CAP encourages one service per use case / persona, each a facade of projections on the same entities – the same idea as RAP projection views and service definitions on top of the interface layer.

One domain model, many services: RepService at /odata/v4/rep for sales reps, ManagerService at /odata/v4/manager with approve and reject, optional AdminService for code lists; all are projections on db/schema.cds
// srv/rep-service.cds
using { sap.capire.orderapproval as my } from '../db/schema';

service RepService @(requires: 'Rep') {              // served at /odata/v4/rep
@odata.draft.enabled                               // 06 · Fiori Elements & Draft
entity ApprovalRequests as projection on my.ApprovalRequests;
@readonly entity RequestTypes as projection on my.RequestTypes;
function openCount() returns Integer;              // implemented on 04 · Custom Logic
}

// srv/manager-service.cds
using { sap.capire.orderapproval as my } from '../db/schema';

service ManagerService @(requires: 'Manager') {      // served at /odata/v4/manager
entity ApprovalRequests as projection on my.ApprovalRequests {
*, customer.name as customerName                 // flatten a path into the projection
} excluding { createdBy, modifiedBy }
actions {
action approve();                              // bound actions (CR4, 04 · Custom Logic)
action reject(reason : String(255));
};
entity Decisions as projection on my.Decisions;
}
  • The service name decides the path: lower case, trailing Service removed → /odata/v4/rep, /odata/v4/manager.
  • Authorization (@requires, @restrict) is explained once on 07 · Authorization & Security; it appears here only to show where it sits.

Part 2 – Service definitions and projections

Entities in a service are usually projections (views) on domain entities. A projection can rename, hide, add calculated columns, filter rows and change annotations – without copying data.

Construct

Example

Effect

Plain projection

entity ApprovalRequests as projection on my.ApprovalRequests;

All elements, all rows; writable

Select columns / alias

as projection on my.ApprovalRequests { ID, salesOrder, status }

Only these elements in the API

excluding

{ * } excluding { createdBy, modifiedBy }

All but the listed elements

Path flattening

{ *, customer.name as customerName }

Read-only column from an association

Row filter

as select from my.ApprovalRequests where status = 'N'

View with a WHERE – read-only unless CAP can resolve it for writes

@readonly / @insertonly

@readonly entity RequestTypes as projection on …;

Only READ / only CREATE accepted (generic 405 otherwise)

Actions and functions

actions { action approve(); }, function openCount() …

Custom operations; implemented on 04 · Custom Logic

Events

event OrderApproved : { salesOrder : String(10); }

Declared payload for messaging (10 · Messaging)

2.1 Auto-exposure and redirection

  • Auto-exposure: when an exposed entity has a composition (notes, decisions), CAP exposes the children automatically. Targets annotated @cds.autoexpose (code lists from @sap/cds/common are) are added read-only when an exposed entity points to them.
  • Auto-redirection: associations in a projection are redirected to the projection of the target in the same service – RepService.ApprovalRequests.notes points to RepService.Notes, not to the domain entity.
  • If there are two projections on the same target in one service, CAP cannot choose: redirect explicitly with redirected to or mark one with @cds.redirection.target.
service ManagerService {
entity ApprovalRequests as projection on my.ApprovalRequests;
entity OpenRequests     as projection on my.ApprovalRequests where status = 'N';
// two projections on the same entity: tell CAP which one associations should point to
annotate ApprovalRequests with @cds.redirection.target;
}

Common mistakes: exposing the domain entity directly with every technical field; one "god service" for all personas (authorization becomes a maze); forgetting that a projection with a WHERE clause may no longer be writable.

Part 3 – Protocols and endpoints: OData V4, REST and more

A service is protocol-neutral. Protocol adapters serve it: OData V4 is the default, REST is built in, GraphQL comes as the open-source plugin @cap-js/graphql. Annotations choose protocol and path.

service RepService { … }                                   // default: /odata/v4/rep

@protocol: 'rest'
service ReportingService { … }                             // /rest/reporting

@protocol: ['odata', 'rest']
service ManagerService { … }                               // /odata/v4/manager and /rest/manager

@path: 'approvals'
service ManagerService { … }                               // /odata/v4/approvals

@protocol: 'none'
service InternalService { … }                              // not reachable over HTTP, only in-process

Protocol

Default path

When to use

OData V4

/odata/v4/<service>

Fiori elements, SAP Build Apps, anything that wants $filter, $expand, draft and annotations

REST

/rest/<service>

Simple JSON clients, webhooks, other teams' microservices

OData V2

via the community adapter @cap-js-community/odata-v2-adapter (Node.js); built into CAP Java

Only for old UI5 apps or tools that need V2

GraphQL

@graphql on the service (plugin @cap-js/graphql)

Clients that prefer GraphQL; Node.js only, plugin still 0.x

Internal

@protocol: 'none'

Services only called from other services

3.1 API documentation for free

cds compile srv --to edmx           # OData $metadata (also: GET /odata/v4/rep/$metadata)
cds compile srv --to openapi        # OpenAPI document, e.g. for API management or SAP Build
cds compile srv --to asyncapi       # events as AsyncAPI (10 · Messaging)

Interview tip: "Why OData V4 and not plain REST?" – Fiori elements and many SAP tools need OData metadata and annotations; querying ($filter, $expand, $search, paging) comes standardised, and CAP serves REST in parallel if another consumer needs it.

Part 4 – Generic providers: served out of the box

As soon as an entity is in a service, CAP's generic handlers answer CRUD requests on it – no code. They translate OData queries into CQL and SQL, apply managed fields, defaults and validation, and run everything in one transaction. Custom handlers only add to or replace this behaviour (04 · Custom Logic in Node.js).

Generic providers: READ with filter, order, top and expand becomes one SQL query with implicit paging; search; deep insert with UUIDs and managed fields; update with ETag check and HTTP 412; delete cascades to compositions; $metadata

Feature

What CAP does

How you influence it

CRUD

READ, CREATE, UPDATE (PATCH / PUT), DELETE on every exposed entity

@readonly, @insertonly, @restrict

Deep read / write

$expand and nested payloads along compositions in one request

Model compositions (02 · CDS Modeling)

Auto-generated keys

UUID keys filled on CREATE

aspect cuid

Managed data

createdAt / By, modifiedAt / By

aspect managed, @cds.on.insert / update

Search

$search over String elements

@cds.search: { salesOrder, customer.name }; fuzzy on SAP HANA Cloud

Paging

Server-side limit, @odata.nextLink for the next page; maximum 1000 rows by default

cds.query.limit.default / .max or @cds.query.limit

Sorting

Implicit sorting by key for stable paging

$orderby

Optimistic locking

ETag in responses, If-Match checked, HTTP 412 on conflict

annotate ApprovalRequests with { modifiedAt @odata.etag }

Input validation

@mandatory, @readonly, @assert … (Part 5)

Annotations

Localized data

Texts in the user's language

localized elements

Draft

Edit / save / discard choreography for Fiori

@odata.draft.enabled (06 · Fiori)

4.1 Paging limits in practice

// package.json – project-wide
"cds": { "query": { "limit": { "default": 50, "max": 500 } } }

// or per service / entity
annotate ManagerService.ApprovalRequests with @cds.query.limit: { default: 20, max: 100 };

Common mistakes: writing a READ handler that re-implements filtering and paging (you lose $filter, $search, paging and authorization filters); expecting more than the maximum page size in one response; no ETag on entities edited by several people.

Part 5 – Generic input validation

Input checks are generic features too. Declare them as annotations on the service entities (or on the domain entities, from where they are inherited by every projection). CAP checks them on every CREATE and UPDATE, rejects the request with a message and rolls the transaction back. Only rules that need logic go into code.

Input validation ladder: 1 static annotations @mandatory, @assert.format, @assert.range, @assert.target; 2 @assert expressions pushed to the database; 3 before handler for logic; 4 database constraints for integrity

Annotation

Checks

Example

@mandatory

Value present and not empty

salesOrder @mandatory

@readonly

Client values silently ignored on CREATE / UPDATE

status @readonly

@assert.range

Numbers and dates within [min, max]; open intervals (0), infinity _ (Node.js 8.5+, Java 3.5+); true for enum values only

netAmount @assert.range: [(0), _]

@assert.format

Regular expression for strings

salesOrder @assert.format: '^[0-9]{1,10}$'

@assert.target

Target of a managed to-one association exists

type @assert.target

@assert: (case … end)

Any condition in CDS expression language, also across fields and associations; pushed down to the database

see below

// srv/constraints.cds – keep constraints in their own file
using { RepService } from './rep-service';
using { ManagerService } from './manager-service';

annotate RepService.ApprovalRequests with {
salesOrder @mandatory @assert.format: '^[0-9]{1,10}$';
netAmount  @assert.range: [(0), _];
deadline   @assert: (case
when deadline < $now then 'DEADLINE_IN_PAST'              // i18n key or plain text
end);
status     @readonly;
}

annotate ManagerService.ApprovalRequests with {
reason @assert: (case
when status = 'R' and (reason is null or trim(reason) = '') then 'REASON_REQUIRED'
end);
}
  • @assert: (case … end) constraints (capire, Declarative Constraints) are collected into one validation query that runs on the database after the INSERT/UPDATE; if a branch returns a message, the request is rejected and the transaction rolled back.
  • Messages can be plain text or keys from _i18n/messages.properties (or i18n.properties); custom texts for the classic annotations via @mandatory.message, @assert.range.message, @assert.format.message.
  • For Fiori, CAP adds the target so the message appears at the field. During draft editing the checks produce messages but keep the draft (06 · Fiori).
  • @assert.integrity / database constraints protect referential integrity against programming errors – not meant for end-user messages.

The coded part of CR3 – "set status and deadline automatically", checks that need other services – is on CAP › 04 · Custom Logic in Node.js.

Part 6 – Trying a service: index page, .http files, curl

Three ways to call RepService locally (after cds watch):

### test/rep.http  (cds add http creates such files; run with the REST Client extension)
GET  http://localhost:4004/odata/v4/rep/ApprovalRequests?$filter=status eq 'N'&$expand=notes
Authorization: Basic mia:

### create with a deep insert
POST  http://localhost:4004/odata/v4/rep/ApprovalRequests
Authorization: Basic mia:
Content-Type: application/json

{ "salesOrder": "4711", "netAmount": 12400, "currency_code": "EUR",
"notes": [ { "text": "Customer asked for 60 days payment terms" } ] }
  • mia is a mock user you define with role Rep (07 · Authorization); mock users need basic authentication with an empty password locally.
  • The index page at http://localhost:4004 lists every service and entity with links to data, $metadata and the Fiori preview.
  • Automated tests with cds.test are on 12 · Testing; calling one service from another in code (cds.connect.to) on 04 · Custom Logic.

Part 7 – Interview questions

Q1. Why define several services on one domain model?

Each service is a facade for one persona or use case: it exposes only the needed entities and fields, carries its own authorization, actions and annotations, and can evolve independently. The domain model stays free of UI and access concerns.

Q2. What does "as projection on" give you compared with copying the entity?

A view, not a copy: you can select, rename, exclude and flatten elements, filter rows and add annotations, while data stays in one table. Associations are auto-redirected to projections in the same service, and simple projections stay writable.

Q3. What are generic providers?

CAP's built-in handlers that serve CRUD, deep reads and writes, search, paging, sorting, ETags, managed fields, defaults, validation, localized data and draft for every exposed entity without code. Custom handlers add logic before, on or after them.

Q4. How do you serve a service as REST instead of OData, or at another path?

@protocol: 'rest' (or the shortcut @rest) – served at /rest/<name>; @protocol: ['odata', 'rest'] serves both; @path: 'approvals' changes the path; @protocol: 'none' makes it internal.

Q5. How does CAP page results and how do you change the limits?

Implicit server-side paging with @odata.nextLink; the maximum page size is 1000 by default. Change it with cds.query.limit.default / .max in the configuration or @cds.query.limit on a service or entity.

Q6. How does optimistic locking work in CAP?

Annotate an element (usually modifiedAt) with @odata.etag. Responses carry the ETag; clients send If-Match; if the row changed meanwhile, CAP answers HTTP 412 Precondition Failed.

Q7. Which validations can you declare instead of coding?

@mandatory, @readonly, @assert.range, @assert.format, @assert.target, and in newer versions @assert with case expressions for cross-field and cross-entity rules pushed down to the database. Messages can be i18n keys; Fiori shows them at the field.

Q8. What is auto-redirection and when do you need @cds.redirection.target?

Associations in service projections are redirected to the projection of their target in the same service. If two projections exist for the same target, CAP cannot choose – mark one with @cds.redirection.target or use redirected to explicitly.

Q9. Scenario: a rep reports that the list stops after 1000 requests. What happened?

The client ignores @odata.nextLink and only reads the first page; CAP's default maximum page size is 1000. Fix the client to follow the next link (Fiori does), or raise / lower the limit deliberately with @cds.query.limit – never return unbounded result sets.

Q10. Scenario: managers must see open requests with the customer name, but must never change a request directly – only through Approve / Reject. How do you model ManagerService?

A projection on ApprovalRequests with customer.name as customerName and without technical fields, plus bound actions approve() and reject(reason). Then restrict it to @restrict: [{ grant: ['READ', 'approve', 'reject'], to: 'Manager' }] (07 · Authorization): generic UPDATE and DELETE are not granted, so the status changes only through the actions (04 · Custom Logic). Plain @readonly is not enough – it equals grant: 'READ' and would block the actions too.

🏠 Start Here · ◀ 02 · CDS Modeling · 04 · Node.js Logic ▶ · Sections: CORE ABAP | OOPS ABAP | ABAP on HANA | Clean Core | RAP | ABAP Points | SAP Fiori | SAPUI5 | Mobile Development (MDK) | BTP Foundations | BTP Development | CAP | SAP Build | ABAP on BTP | Integration Suite | SAP Business AI | SAP BASIS | Security | SAP SDLC

Functional: FICO ABAP | TRM ABAP | VIM | SAP BIS | SD ABAP | MM ABAP | PP ABAP | QM ABAP | PM ABAP | PS ABAP | EWM | TM ABAP | EHS ABAP | HR ABAP | BW | SAP MDG | SAP Analytics Cloud | SAP Ariba | SAP CX | SAP IBP