Hello World!
Let's create a simple Hello World OData service using the SAP Cloud Application Programming Model in six lines of code and in under 2 minutes.
You can also download the sample from github.com.
Let's create a simple Hello World OData service using the SAP Cloud Application Programming Model with a few lines of code and in under 2 minutes.
This guide is available for Node.js and Java.
Use the toggle in the title bar or press v to switch.
This guide is available as a CAP Notebook.
Download the notebook to run it locally in your VS Code editor.
Create a Project
cds init hello-world
cd hello-world
cds init hello-world --java --java:mvn -DgroupId=com.sap.capire --add tiny-sample
cd hello-world
With the
cds init
command above you also created a sample schema and service. It's not relevant and can be ignored for now, but a CAP Java service currently needs persistence in order to startup correctly.
Define a Service
... using CDS:
service say {
function hello (to:String) returns String;
}
Implement it
... for example, using Node.js express.js handlers style.
module.exports = (say)=>{
say.on ('hello', req => `Hello ${req.data.to}!`)
}
... or Node.js ES6 classes style.
module.exports = class say {
hello(req) { return `Hello ${req.data.to}!` }
}
That has limited flexibility, for example, you can register only one handler per event.
... for example, using a CAP Java custom handler like this:
package com.sap.capire.hello_world.handlers;
import org.springframework.stereotype.Component;
import com.sap.cds.services.handler.EventHandler;
import com.sap.cds.services.handler.annotations.On;
import com.sap.cds.services.handler.annotations.ServiceName;
import cds.gen.say.HelloContext;
import cds.gen.say.Say_;
@Component
@ServiceName(Say_.CDS_NAME)
public class HelloHandler implements EventHandler {
@On
public void onHello(HelloContext ctx) {
ctx.setResult("Hello " + ctx.getTo());
ctx.setCompleted();
}
}
Run it
... for example, from your command line in the root directory of your "Hello World":
cds watch
cd srv
mvn cds:watch
Consume it
... for example, from your browser:
http://localhost:4004/odata/v4/say/hello(to='world')
http://localhost:8080/odata/v4/say/hello(to='world')
You should see the value "Hello world!" being returned.