k

Kikaha

blog source code

Consider that you need to create a REST API to include and retrieve users. Just for the sake of this example we will persist it in a Map.

We will assume you have installed the Command line interface tool before you have started following this tutorial.

First of all, create an empty-project called user-sample.

# create the project
kikaha project create 2.1 --name=user-sample
# enter into the project folder
cd user-sample

This will create a project with basic libraries, including JSON serialization support.

Then, create the User class.

package sample.user;

public class User {

    // The ID will be auto-generated just for the sake of this sample.
    final Long id = System.currentTimeMillis();
    String name;

    public String getName(){ return name; }
    public void setName( String name ){
        this.name = name;
    }
}

Now, lets create our first route class (UserResource class).

package sample.user;

import java.util.*;
import javax.inject.*;
import kikaha.urouting.api.*;

@Path( "users" )
@Produces( Mimes.JSON )
@Singleton
public class UserResource {

    final Map<Long, User> users = new HashMap<Long, User>();

    @GET
      public Collection<User> retrieveAllUsers(){
      return users.values();
    }

    @GET
    @Path( "{id}" )
    public User retrieveUserById(
            @PathParam( "id" ) Long id ) {
        return users.get( id );
    }

    @POST
    @Path( "{id}" )
    @Consumes( Mimes.JSON )
    public void persistUser( User user ) {
        users.put( user.getId(), user );
    }
}

Now, type kikaha run-app to run your application. And that's it! We just have created a REST endpoint where you are able to:

  • POST an User as JSON at http://localhost:9000/users/
  • GET all registered users at http://localhost:9000/users/
  • GET a JSON representation of User, searching by id by at http://localhost:9000/users/{the-user-id}.

Next steps

Now that you have created your first project, you may be interested in: