SAP Guide: Model a Domain and Add Custom Logic in CAP

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Checked on 2026-11-13 against CAP Node.js 10.2 (@sap/cds 10.2.2, @sap/cds-dk 10.2.1) and Node.js 24.21.

What you build

This is a teaching model built with CAP. It is not SAP S/4HANA or SAP SuccessFactors and does not reproduce their screens.

You build a small service for expense claims in which a claim is made of parts. A claim has several items, and each item points at a category from a short list. You describe this in CDS with a composition (the items belong to their claim), an association (an item refers to a category that lives on its own) and two ready-made building blocks, cuid and managed. Then you add two pieces of custom logic in JavaScript: a validation handler that refuses bad claims and sums the total, and an action submit that moves a claim from the status N (new) to S (submitted). You try everything with curl.

Terminal with the call of the action submit on the claim Customer visit Chicago: the first call answers HTTP 200 with the claim, whose status is now S and whose total is 128.50, and the second call answers HTTP 409 with the message Claim is already submitted (status S)

Before you start

  • No account is needed: the CAP tools install from the public npm registry without signing in. Installing @sap/cds-dk and @sap/cds means accepting the SAP Developer License Agreement, version 3.2, which the packages state themselves; the lab README names it.

  • Install Node.js 22.12 or newer (node -v prints the version) and the CAP command line tools (npm install --global @sap/cds-dk, as in the guide Your First CAP Service). Use a code editor such as Visual Studio Code and a terminal.

  • curl must be version 7.82 or newer, because the guide uses its option --json. curl --version shows it.

  • Read CAP Domain Modeling and Services and Custom Handlers in Node.js first, or at least know what an entity, an association and an event handler are. The guide Your First CAP Service builds a smaller project in the same way, and you can do it first.

  • The project is built from cds init, so nothing from an earlier guide is needed. The names Categories, Claims and ClaimItems, the category codes and the amounts are the model’s own and are made up. cuid, managed, Composition, Association and @assert.target come from the CAP documentation pages listed under Sources. The status codes N and S are made up as well.

  • The figures are drawings of the editor, the terminal and the browser, not screenshots. A highlighted box with a number marks the file, the line or the address of the step with the same number.

Steps

Create the project and the model

  1. Create the project, install its dependencies and open the folder in your editor (in Visual Studio Code, code .):

    cds init claims --nodejs
    cd claims
    npm install

    cds init prints Successfully initialized CAP project and creates the folders app, db and srv.

  2. Create the file db/schema.cds. The first line imports cuid and managed from CAP. cuid adds a key ID that CAP fills with a new unique value. managed adds the fields createdAt, createdBy, modifiedAt and modifiedBy, which CAP fills for you. The file then defines three entities:

    • Categories is a small reference list. Its key is a code that you choose, such as TRAVEL.

    • Claims has a title, a status that starts as N and a total. The line items : Composition of many ClaimItems on items.claim = $self says that the items are parts of the claim: they are created, read and deleted together with it. The on condition names the backlink claim, which is the association on the item.

    • ClaimItems has a description and an amount, an association claim back to its claim and an association category to the reference entity. The annotation @assert.target makes CAP check that the category exists when an item is written.

      using { cuid, managed } from '@sap/cds/common';
      namespace sap.guide.claimsmodel;
      
      entity Categories {
        key code : String(10);
        name     : String(40);
      }
      
      entity Claims : cuid, managed {
        title  : String(80);
        status : String(1) default 'N';
        total  : Decimal(9,2);
        items  : Composition of many ClaimItems on items.claim = $self;
      }
      
      entity ClaimItems : cuid {
        claim       : Association to Claims;
        category    : Association to Categories @assert.target;
        description : String(80);
        amount      : Decimal(9,2);
      }
      Visual Studio Code with the file db/schema.cds open: it imports cuid and managed, sets the namespace sap.guide.claimsmodel and defines the entities Categories with the key code, Claims with the composition items, and ClaimItems with the associations claim and category; callout 2 marks the file in the explorer

Expose the model and add data

  1. Create the file srv/claims-service.cds. A service is a window onto the data. Claims and Categories are listed as projections, which show the fields unchanged. ClaimItems is not listed, because it is a composition target: CAP exposes it by itself, but only through its claim.

    using { sap.guide.claimsmodel as db } from '../db/schema';
    
    service ClaimsService {
      entity Claims     as projection on db.Claims;
      entity Categories as projection on db.Categories;
    
    }
  2. Create the folder db/data and in it three CSV files. CAP loads every CSV file in db/data into the database when the server starts. A file name is the namespace, a dash and the entity name, and the first row names the fields. The foreign keys of an association have the name of the association, an underscore and the name of the target’s key: claim_ID and category_code. The two claims have fixed IDs so that later commands can name them: the first is new (N), the second is already submitted (S).

    db/data/sap.guide.claimsmodel-Categories.csv:

    code,name
    TRAVEL,Travel
    MEALS,Meals
    LODGING,Lodging

    db/data/sap.guide.claimsmodel-Claims.csv:

    ID,title,status,total
    a1111111-1111-1111-1111-111111111111,Customer visit Chicago,N,128.50
    a2222222-2222-2222-2222-222222222222,Warehouse audit Denver,S,210.00

    db/data/sap.guide.claimsmodel-ClaimItems.csv:

    ID,claim_ID,category_code,description,amount
    b1111111-1111-1111-1111-111111111111,a1111111-1111-1111-1111-111111111111,TRAVEL,Train ticket,98.50
    b2222222-2222-2222-2222-222222222222,a1111111-1111-1111-1111-111111111111,MEALS,Client dinner,30.00
    b3333333-3333-3333-3333-333333333333,a2222222-2222-2222-2222-222222222222,LODGING,Two nights,210.00
    Visual Studio Code with the file srv/claims-service.cds open: the service ClaimsService exposes the entities Claims and Categories as projections on db.Claims and db.Categories; callout 3 marks the service file and callout 4 marks the folder db/data, which holds the three CSV files

Run the service

  1. In the terminal, in the project folder, start the server in watch mode. Leave it running: cds watch restarts the server whenever you save a file.

    cds watch
  2. Read the log. CAP loads the model files, connects to a database that lives only in memory and fills it from your three CSV files. The service is served at /odata/v4/claims (CAP derives claims from the name ClaimsService) on http://localhost:4004. The line using auth strategy { kind: 'mocked' } says that no real login is used while you develop.

    Terminal after cds watch: the log lists the model files srv/claims-service.cds, db/schema.cds and the common.cds of CAP, connects to an in-memory SQLite database, initializes it from the three CSV files for Claims, ClaimItems and Categories, serves ClaimsService at /odata/v4/claims and ends with server listening on http://localhost:4004; callout 5 marks the command and callout 6 the lines that load the CSV files

    The figure leaves out the banner that cds watch prints before the first line, a line about service bindings that your machine may or may not print, and the last line, which names the start time.

Read the structure

  1. Open the claim together with its items and their categories in the browser. The query option $expand follows a relation and returns the related rows inside the answer: items is the composition and category is the association of each item. Open http://localhost:4004/odata/v4/claims/Claims?$top=1&$select=title&$expand=items($select=description;$expand=category). The answer holds the claim Customer visit Chicago with its two items, and each item carries its category with the code and the name from the reference list. The key ID is always part of an answer.

    Browser with the address localhost:4004/odata/v4/claims/Claims with the query options top, select and expand, marked by callout 7: the JSON response holds one claim, Customer visit Chicago, with its two items, the Train ticket in the category TRAVEL named Travel and the Client dinner in the category MEALS named Meals
  2. Ask for the items directly. You did not list ClaimItems in the service, and CAP refuses a direct request, because a composition target is reachable only through its parent. The single quotes keep the shell from touching the address.

    curl -s -i 'localhost:4004/odata/v4/claims/ClaimItems' | grep -E "^(HTTP|\{)"
    HTTP/1.1 405 Method Not Allowed
    {"error":{"message":"Entity \"ClaimsService.ClaimItems\" is not explicitly exposed as part of the service","code":"ENTITY_IS_AUTOEXPOSED","@Common.numericSeverity":4}}

Add a validation handler

The model cannot say that an item must cost something or that a claim needs a title. Such rules go into an event handler, a small function that CAP calls at a defined moment while it processes a request.

  1. Create the file srv/claims-service.js, next to the service definition and with the same name. CAP finds it by that name. The class extends cds.ApplicationService, which brings the built-in reading and writing, and attaches the function validateClaim for the phase before of the events CREATE and UPDATE on Claims. The function reports each broken rule with req.error, which records the error and goes on, so that the user sees all of them at once. When the request carries items, it also sets the total to the sum of their amounts. The amounts are added in whole cents, so that the sum is exact.

    import cds from '@sap/cds'
    
    export default class ClaimsService extends cds.ApplicationService {
      init() {
        this.before(['CREATE', 'UPDATE'], 'Claims', validateClaim)
        return super.init()
      }
    }
    
    // Money is summed in whole cents so that the total is exact.
    const cents = (amount) => Math.round(Number(amount) * 100)
    
    function validateClaim(req) {
      const { title, items } = req.data
      if (req.event === 'CREATE' && !title?.trim()) {
        req.error(400, 'A claim needs a title', 'in/title')
      }
      if (items === undefined) return
      if (items.length === 0) {
        req.error(400, 'A claim needs at least one item', 'in/items')
      }
      for (const item of items) {
        if (!(cents(item.amount) > 0)) {
          const name = item.description
          req.error(400, `Item "${name}" needs an amount above zero`, 'in/items')
        }
      }
      const sum = items.reduce((total, item) => total + cents(item.amount), 0)
      req.data.total = (sum / 100).toFixed(2)
    }
    Visual Studio Code with the file srv/claims-service.js open: the class ClaimsService attaches the function validateClaim as a before handler for CREATE and UPDATE of Claims, and validateClaim checks the title, the items and each item amount and sums the total in cents; callout 9 marks the file in the explorer
  2. Save the file. cds watch restarts, and its log now shows the line impl: 'srv/claims-service.js' next to the service. Create the folder http and in it the file http/new-claim.json, a claim with two items. One request creates the claim and its items together, which is called a deep insert, and the claim has no total yet:

    {
      "title": "Supplier meeting Austin",
      "items": [
        { "category_code": "TRAVEL", "description": "Flight", "amount": 220.00 },
        { "category_code": "MEALS", "description": "Lunch", "amount": 24.75 }
      ]
    }

    Post it. The handler fills the total, status keeps its default N, and CAP adds the ID values and the managed fields. The ID values and the time stamps of your run differ from the ones shown here.

    curl -s -i --json @http/new-claim.json localhost:4004/odata/v4/claims/Claims | grep -E "^(HTTP|\{)"
    HTTP/1.1 201 Created
    {"@odata.context":"$metadata#Claims/$entity","ID":"4e105e1f-8b51-4d35-853e-1a1cea101f41","createdAt":"2026-11-13T18:48:01.093Z","createdBy":"anonymous","modifiedAt":"2026-11-13T18:48:01.093Z","modifiedBy":"anonymous","title":"Supplier meeting Austin","status":"N","total":"244.75","items":[{"ID":"61b13497-480e-4d80-a752-1b2d34e610c8","claim_ID":"4e105e1f-8b51-4d35-853e-1a1cea101f41","category_code":"TRAVEL","description":"Flight","amount":"220.00"},{"ID":"1146d853-9b7e-4d7e-9c2e-49388683cdc9","claim_ID":"4e105e1f-8b51-4d35-853e-1a1cea101f41","category_code":"MEALS","description":"Lunch","amount":"24.75"}]}

    The total is 244.75, the sum of 220.00 and 24.75. You sent no total, and the items got their claim_ID from the composition.

  3. Create http/bad-claim.json, a claim whose only item has a negative amount, and post it. The handler refuses the request with HTTP 400 and the message that it wrote.

    {
      "title": "Taxi rides",
      "items": [
        { "category_code": "TRAVEL", "description": "Airport taxi", "amount": -18.00 }
      ]
    }
    curl -s -i --json @http/bad-claim.json localhost:4004/odata/v4/claims/Claims | grep -E "^(HTTP|\{)"
  4. Create http/empty-claim.json, a claim with a blank title and no items, and post it. It breaks two rules, and the answer holds both: the code MULTIPLE_ERRORS and a list details with one entry for each req.error call, each with its own target.

    {
      "title": " ",
      "items": []
    }
    curl -s -i --json @http/empty-claim.json localhost:4004/odata/v4/claims/Claims | grep -E "^(HTTP|\{)"
    Terminal with two curl requests that the handler refuses: the first, for bad-claim.json, answers HTTP 400 with the message that the item Airport taxi needs an amount above zero, marked by callout 11; the second, for empty-claim.json, answers HTTP 400 with the code MULTIPLE_ERRORS and two details, a claim needs a title and a claim needs at least one item, marked by callout 12

    Each answer is cut to the status line and the body, and the figure wraps the long lines the way a terminal does.

Add an action

An action is an operation that the service offers besides reading and writing. A bound action works on one row of an entity: here submit works on one claim.

  1. Open srv/claims-service.cds and add the block at the end of the service. It declares the action submit on Claims. The action takes no input and returns the claim. The file now reads:

    using { sap.guide.claimsmodel as db } from '../db/schema';
    
    service ClaimsService {
      entity Claims     as projection on db.Claims;
      entity Categories as projection on db.Categories;
    
      // tag::action[]
      extend entity Claims with actions {
        action submit() returns Claims;
      }
      // end::action[]
    }
  2. Open srv/claims-service.js. In init(), add one line before return super.init(). It attaches the function submitClaim for the event submit of Claims, with on, the phase that does the work of a request:

        this.on('submit', 'Claims', submitClaim)

    At the end of the file, add the function itself. req.subject is a reference to the one row that the request addresses, so SELECT.one.from(req.subject) reads the claim. A claim whose status is not N is refused with req.reject, which throws the error at once, and the status 409 means conflict. Otherwise the function sets the status to S and returns the claim.

    async function submitClaim(req) {
      const { Claims } = this.entities
      const claim = await SELECT.one.from(req.subject)
      if (!claim) return req.reject(404, 'Claim not found')
      if (claim.status !== 'N') {
        const message = `Claim is already submitted (status ${claim.status})`
        return req.reject(409, message)
      }
      await UPDATE(Claims, claim.ID).with({ status: 'S' })
      return SELECT.one.from(Claims, claim.ID)
    }
    Visual Studio Code with the file srv/claims-service.js open, shown as an excerpt: the class attaches submitClaim with this.on for the action submit of Claims, and the function submitClaim reads the claim with req.subject, refuses a claim whose status is not N with HTTP 409 and otherwise sets the status to S and returns the claim; callout 14 marks the file in the explorer
  3. Call the action. In OData a bound action is called with a POST to the row’s address followed by the service name and the action name. The shell treats the parentheses of that address in its own way, so keep the address in single quotes. Put it into a variable, call it, and call it again:

    URL='localhost:4004/odata/v4/claims/Claims(a1111111-1111-1111-1111-111111111111)/ClaimsService.submit'
    curl -s -i --json '{}' "$URL" | grep -E "^(HTTP|\{)"
    curl -s -i --json '{}' "$URL" | grep -E "^(HTTP|\{)"

    The first call answers HTTP 200 with the claim, and its status is now S. The second call answers HTTP 409 with the message Claim is already submitted (status S). The same call for the second claim of the CSV file answers 409 at once, because that claim was submitted from the start. The result is the figure at the top of this guide.

Check the result

  • The log of cds watch shows the lines impl: 'srv/claims-service.js' and server listening and no line that starts with [ERROR].

  • The expand request returns the claim Customer visit Chicago with two items, each with its category.

  • A claim with an item amount of zero or less, or with no title or no items, is refused with HTTP 400, and a valid claim answers 201 with the total filled in.

  • The first submit answers 200 and status S; the second answers 409.

Variations

  • Look at the effect of @assert.target. With the annotation in place, post a claim with an item whose category_code is NOPE: the answer is HTTP 400 with the code ASSERT_TARGET and the message Target with this key doesn't exist. Remove the annotation, save, and post the same request again: it answers 201 Created and stores the item with a category that does not exist. An association alone does not check its target.

  • Put the rules under test. Install the test helper with npm install --save-dev @cap-js/cds-test, add the script "test": "node --test" to package.json (npm pkg set scripts.test="node --test" does it), create test/service.test.js and run npm test. The file starts a server of its own on a free port, so cds watch may keep running. The listing is the lab’s test file:

    import cds from '@sap/cds'
    import { test } from 'node:test'
    import assert from 'node:assert'
    const { GET, POST } = cds.test(import.meta.dirname + '/..')
    const base = '/odata/v4/claims'
    const one = 'a1111111-1111-1111-1111-111111111111'
    const two = 'a2222222-2222-2222-2222-222222222222'
    const item = (description, amount, category_code = 'TRAVEL') =>
      ({ description, amount, category_code })
    const rejected = async (path, body) => {
      try {
        await POST(path, body)
        assert.fail('should be rejected')
      } catch (e) {
        return e.response ?? e
      }
    }
    test('reads a claim with its items and their categories', async () => {
      const query = '$expand=items($expand=category)&$orderby=title'
      const { data } = await GET(`${base}/Claims?${query}`)
      assert.equal(data.value.length, 2)
      assert.equal(data.value[0].items.length, 2)
      assert.equal(data.value[0].items[0].category.name, 'Travel')
    })
    test('posts a claim with items in one request and sums the total', async () => {
      const items = [item('Flight', 220), item('Lunch', 24.75, 'MEALS')]
      const { status, data } = await POST(`${base}/Claims`, { title: 'Trip', items })
      assert.equal(status, 201)
      assert.equal(data.total, '244.75')
      assert.equal(data.status, 'N')
      assert.equal(data.items.length, 2)
    })
    test('rejects an item with an amount of zero or less', async () => {
      const body = { title: 'Taxi', items: [item('Ride', -18)] }
      const r = await rejected(`${base}/Claims`, body)
      assert.equal(r.status, 400)
      assert.match(r.data.error.message, /Item "Ride" needs an amount above zero/)
    })
    test('collects several errors in one answer', async () => {
      const r = await rejected(`${base}/Claims`, { title: ' ', items: [] })
      assert.equal(r.status, 400)
      assert.equal(r.data.error.code, 'MULTIPLE_ERRORS')
      assert.equal(r.data.error.details.length, 2)
    })
    test('rejects an item with an unknown category', async () => {
      const body = { title: 'Odd', items: [item('X', 5, 'NOPE')] }
      const r = await rejected(`${base}/Claims`, body)
      assert.equal(r.status, 400)
      assert.equal(r.data.error.code, 'ASSERT_TARGET')
    })
    test('submits a new claim once, then refuses a second submit', async () => {
      const url = `${base}/Claims(${one})/ClaimsService.submit`
      const { status, data } = await POST(url, {})
      assert.equal(status, 200)
      assert.equal(data.status, 'S')
      const again = await rejected(url, {})
      assert.equal(again.status, 409)
      assert.match(again.data.error.message, /already submitted/)
    })
    test('refuses to submit a claim that was submitted before', async () => {
      const r = await rejected(`${base}/Claims(${two})/ClaimsService.submit`, {})
      assert.equal(r.status, 409)
    })

    The run ends with the lines ℹ pass 7 and ℹ fail 0.

What can go wrong

Symptom Cause Fix

zsh: no matches found: localhost:4004/odata/v4/claims/Claims(a1111111-1111-1111-1111-111111111111)/ClaimsService.submit

The shell reads the parentheses, and in other addresses the ? and the $, as its own syntax.

Put the whole address in single quotes, as in step 15.

The log shows [EADDRINUSE] - port 4004 is already in use by another server process.

Another program already listens on port 4004.

Stop that program, or press Return to restart with an arbitrary port and use the port that the log names in every address of this guide.

The claim from bad-claim.json is accepted with HTTP 201, and the action answers HTTP 501 with Service "ClaimsService" has no handler for "submit ClaimsService.Claims".

The handler file is not found. Its name differs from the service file (here claim-service.js instead of claims-service.js), so the log has no impl: line and none of your rules run.

Rename the file to srv/claims-service.js and save. cds watch restarts, and the impl: line appears.

cds watch stops with Error: in cds.deploy(): table sap_guide_claimsmodel_ClaimItems has no column named category

A header in a CSV file names a field that the entity does not have, here category instead of category_code.

Correct the first row of the CSV file so that each name is a field of the entity, and save.

/odata/v4/claims/ClaimItems answers HTTP 405 with the code ENTITY_IS_AUTOEXPOSED

ClaimItems is a composition target, so CAP exposes it only through its parent.

Read it with $expand=items on Claims, or list it explicitly in the service.

A GET on the address of submit answers HTTP 405 Method Not Allowed

An action changes data, so OData calls it with POST.

Send the request with curl --json '{}' ..., which makes it a POST.

A POST to /odata/v4/claims/submit answers HTTP 404 with Invalid resource path "ClaimsService.submit"

submit is bound to Claims, so it needs the address of one claim in front of it.

Use the address of step 15, with the ID of the claim.

Clean up

Press Ctrl+C in the terminal to stop cds watch. The database lived only in memory, so there is nothing to delete. The folder claims is yours to keep.