Tutorials

REST Controller

Introduction

In this tutorial you will:

  • Create a REST controller in your application

  • Configure your Studio image to open an HTTP port to your app

  • Verify operation of your controller

This tutorial builds upon the Hello World App tutorial.

Preliminaries

You should have completed the Hello World tutorial and have it ready to build upon.

The pom.xml, assembly.xml, and descriptor.json files are identical to those in that tutorial.

Java Code

This section describes the Java code you’ll write.

Create controller

In your KOS Java application code, add the following controller class:

MyController class
package com.example;

import com.tccc.kos.commons.core.dispatcher.annotations.ApiController;
import com.tccc.kos.commons.core.dispatcher.annotations.ApiEndpoint;
import com.tccc.kos.commons.core.dispatcher.annotations.PathVariable;
import com.tccc.kos.commons.core.dispatcher.annotations.RequestParam;
import java.util.ArrayList;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;

@ApiController(base = "/mycontroller", title = "My first KOS REST controller")
public class MyController {

    /**
     * GET http://localhost:{port}/api/system/mycontroller/ping
     * returns: {"status":200,"version":{"major":1,"minor":0},"data":"pong"}
     */
    @ApiEndpoint(GET = "/ping", desc = "checks to see if controller is running")
    public String ping() {
        return "pong";
    }

    /**
     * GET http://localhost:{port}/api/system/mycontroller/dosomething
     * returns: {"status":200,"version":{"major":4,"minor":56}}
     */
    @ApiEndpoint(GET = "/dosomething", desc = "returns void", version = "4.56")
    public void doSomething() {
    }

    /**
     * GET http://localhost:{port}/api/system/mycontroller/bean/17
     * returns: {"status":200,"version":{"major":1,"minor":0},"data":{"id":17,"name":"Fred","other":"Flintstone"}}
     */
    @ApiEndpoint(GET = "/bean/{id}", desc = "uses path variable and returns an object")
    public MyBean getBean(@PathVariable("id") Integer id) {
        MyBean myBean = new MyBean(id, "Fred", "Flintstone");
        return myBean;
    }

    /**
     * GET http://localhost:{port}/api/system/mycontroller/user/list?order=firstName&limit=10
     * passes in: the parameter "order" contains "firstName" and the parameter "limit" is "20"
     */
    @ApiEndpoint(GET = "/user/list", desc = "")
    public List<MyBean> listUsers(
            @RequestParam(value = "order", required = true) String order,
            @RequestParam(value = "limit", defaultValue = "20") Integer limit) {
        List<MyBean> list = new ArrayList<>(limit);
        list.add(new MyBean(1, "Fred", "Foo"));
        list.add(new MyBean(2, "Barney", "Bar"));
        return list;
    }

    @Data
    @AllArgsConstructor
    public static class MyBean {
        private int id;
        private String name;
        private String other;
    }
}

Notice that this controller has four endpoints:

  1. ping() accepts no input and returns a string

  2. doSomething() sets the endpoint’s version number and returns null

  3. getBean() accepts a path variable and returns an object

  4. listUsers() accepts two query params and returns a list of objects

Instantiate controller

Before using the controller, we must first instantiate it and tell the KOS context about its existence. We do that by adding one line to the MyKosApp class:

@Slf4j
public class MyKosApp extends SystemApplication<BaseAppConfig> {

    @Override
    public void load() {
        log.info("MyKosApp.load()");
        getCtx().add(new MyController()); (1)
    }

    @Override
    public void start() {
        log.info("MyKosApp.start()");
    }
}
1 Instantiate your controller and add it to the KOS bean context.

Build your code using the standard Maven command line or your IDE.

Studio Changes

In Studio, open the image configuration window and perform the following operations.

Configure HTTP port number

  • Click on the Settings card

  • Click on the Port Mappings tab

  • For the HTTP port, in the Local Override column, enter 8081 as the port number:

port mappings
Figure 1. Port mappings

Setting this "local override" port allows us to access the user interface through a local browser.

Now run your KOS application in the Studio simulator.

Test Endpoints

In this section, we’ll hit the MyController endpoints. Since all are HTTP GET methods, you can use any browser, or you can use an API tool like Postman.

URL format

KOS REST controller URLs have the form:

http://{domain}:{port}/api/{appId}/{base}/{path}

where:
* {domain} is the computer or simulator’s domain name
* {port} is the corresponding HTTP port number
* {appId} is the value found in the descriptor.json file’s kos.app.appId field (in our case it’s "system")
* {base} is the "base" value found in the controller’s @ApiController annotation
* {path} is the path associated with the GET/POST/PUT/DELETE field in the @ApiEndpoint annotation

/ping

When you hit this endpoint:

http://localhost:8081/api/system/mycontroller/ping

You should see this result:

{
  "status": 200, (1)
  "version": {
    "major": 1, (2)
    "minor": 0
  },
  "data": "pong" (3)
}
1 The status code is 200, or commonly known as "OK".
2 When the version parameter is absent, the returned version is "1.0".
3 The data returned is simply a string.

/dosomething

Let’s try something a little different:

http://localhost:8081/api/system/mycontroller/dosomething

You should see the following:

{
  "status": 200,
  "version": {
    "major": 4, (1)
    "minor": 56
  } (2)
}
1 The returned version corresponds to the values used in the annotation.
2 No data is returned, as the endpoint’s return value is void.

/bean

Now let’s pass in a path parameter to our endpoint:

http://localhost:8081/api/system/mycontroller/bean/17

You should see the following:

{
  "status": 200,
  "version": {
    "major": 1,
    "minor": 0
  },
  "data": { (1)
    "id": 17,
    "name": "Fred",
    "other": "Flintstone"
  }
}
1 Data returned is an object.

/list

In this example, query parameters are used in the URL (even though the Java code ignores them).

http://localhost:8081/api/system/mycontroller/user/list?order=firstName&limit=10

You should see:

{
  "status": 200,
  "version": {
    "major": 1,
    "minor": 0
  },
  "data": [ (1)
    {
      "id": 1,
      "name": "Fred",
      "other": "Foo"
    },
    {
      "id": 2,
      "name": "Barney",
      "other": "Bar"
    }
  ]
}
1 Data returned is a list of objects.

Summary

In this tutorial, we added some API endpoints to our KOS application.

For more information about this topic, see the HTTP/REST Controllers page.

Next up, we learn how to debug our Java code.

Previous
Next
On this page
Related Articles
Expand your knowledge with these curated articles that complement your exploration of KOS.
Hello World App
todo - description
How To Debug Code
todo - description
API Endpoints
todo - description
Java Development
Seamlessly transition from Legacy+ systems to Freestyle microdosing and advanced distributed dispense systems.
UI Development
Using KOS SDKs, integrating Consumer and Non-consumer facing UIs becomes seamless, giving you less hassle and more time to create.
Video Library
Meet some of our development team, as they lead you through the tools, features, and tips and tricks of various KOS tools.
Resources
Familiarize yourself with KOS terminology, our reference materials, and explore additional resources that complement your KOS journey.
Copyright © 2024 TCCC. All rights reserved.