Skip to content
Search

    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.

    Initialize the project

    cds init hello-world --add java,samples
    cd hello-world
    

    Define a Service

    … using CDS.

    File srv/world.cds, content:

    service say {
      function hello (to:String) returns String;
    }
    

    Implement it

    … for example, using Node.js express.js handlers style.

    File srv/world.js, content:

    module.exports = (say)=>{
      say.on ('hello', req => `Hello ${req.data.to}!`)
    }
    

    … or Node.js ES6 classes style.

    File srv/world.js, content:

    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:

    File srv/src/main/java/customer/hello_world_java/handlers/HelloWorld.java, content:

    package customer.hello_world_java.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/say/hello(to='world')

    http://localhost:8080/odata/v4/say/hello(to=’world’)

    📓