labs / tiddlers / content / labs / lab08 /

Let's make the service return some products.

  1. Start H2 if you haven't already.

  2. Add a ProductDAO field named productDao to the Server class. Initialise the field with an instance of ProductJdbiDAO (use the factory).

  3. Change the Hello World code in the constructor to:

      get("/api/products", ctx -> productDao.getProducts());
  4. Stop and run the server again. You need to remember to stop the server first since if you try to run it twice you will get a connection error since the port is already in use.

  5. Reload the page in the browser. Append api/products to the URI.

    You should see some products. Jooby is using the toString method to display the products.

    Since we are going to be serving 3 modules (products, customer, and sales) and one web site out of the same web server we need to be careful with the URI paths which is why we now have api/products in the URI.

  6. Add the following to the constructor (below what is already here).

    get("/api/products/{id}", ctx -> {
        String id = ctx.path("id").value();
        Product product = productDao.searchById(id);
        if(product == null) {
            // no product with that ID found, so return a 404/Not Found error
            return ctx.send(StatusCode.NOT_FOUND);
        } else {
            return product;

    The variable ctx holds the HTTP context which includes the request details. In this case we are extracting a path parameter named id out of the context.

    If a non-existent ID is provided then the service should return a 404/Not Found response rather than a null.

  7. Stop and run. Append a product ID for a product that exists in your database to the end of the URI in the browser. You should see the details for a that product appear in the browser.

    The ID that you added to the end of the URI becomes the id path parameter.