Quick REST demo with Spark

What is Spark? If we take a look to the project’s web page, it says something like “Spark is a simple and lightweight Java web framework built for rapid development“. In other words, it proposes us a simple way to build web applications without dealing with XML or annotations.

I recognize I do not usually use it but I have found it very useful when I need to prepare some REST services for a quick demo. Do not missunderstanding me, I think that use the Java EE platform is amazing and you can develop with it very fast, but you need a server, a couple of classes with the JAX-RS configuration and a few annotations to make everything work. With Spark, you only need to add a dependency in you .pom file and write a few lines of code.

For the example, I am going to implement a little application offering REST services with the CRUD operations for a User. This entity is going to have:

  • id
  • name
  • surname

In first place, we should create a java application in our favorite IDE using maven.

In second place, we are going to add the correct maven dependency for the Spark library.

<dependencies>
    <dependency>
        <groupId>com.sparkjava</groupId>
        <artifactId>spark-core</artifactId>
        <version>2.1</version>
    </dependency>
</dependencies>

In third place, we should create our entity object.

public class User {
    private String id;
    private String name;
    private String surname;
     
    // Getters and setters
}

Now, we need to start to write our main class. In this main class we are going to add a couple of things:

  • A Map to simulate our data store.
  • A main method that it is going to contain our REST services.

The main class looks like:

public class Users {
    private static Map<String, User> users = new HashMap<String, User>();
 
    public static void main(String[] args) {
        final Random random = new Random();
         
        // Services here
    }
}

Now, we are going to start with the services.

/users?name=Foo&surname=Bar (POST)

Spark.post("/users", (request, response) -> {
    String name = request.queryParams("name");
    String surname = request.queryParams("surname");
 
    User user = new User(name, surname);
    int id = random.nextInt(Integer.MAX_VALUE);
     
    users.put(String.valueOf(id), user);
 
    response.status(201); // 201 Created
     
    return id;
});

/users/:id (GET)

Spark.get("/users/:id", (request, response) -> {
    User user = users.get(request.params(":id"));
    if (user != null) {
        return "Name: " + user.getName() + ", Surname: " + user.getSurname();
    } else {
        response.status(404); // 404 Not found
        return "User not found.";
    }
});

/users/:id (PUT)

Spark.put("/users/:id", (request, response) -> {
    String id = request.params(":id");
    User user = users.get(id);
    if (user != null) {
        String newName = request.queryParams("name");
        String newSurname = request.queryParams("surname");
        if (newName != null) {
            user.setName(newName);
        }
        if (newSurname != null) {
            user.setSurname(newSurname);
        }
        return "User with id '" + id + "' has been updated.";
    } else {
        response.status(404); // 404 Not found
        return "User not found.";
    }
});

/users/:id (DELETE)

Spark.delete("/users/:id", (request, response) -> {
    String id = request.params(":id");
 
    User user = users.remove(id);
 
    if (user != null) {
        return "User with id '" + id + "'has been deleted";
    } else {
        response.status(404); // 404 Not found
        return "User not found.";
    }
});

/users (GET)

Spark.get("/users", (request, response) -> {
    String ids = "";
 
    for (String id : users.keySet()) {
        ids += id + " ";
    }
     
    return ids;
});

Now, we only need to execute our application and check if everything is working correctly. To do this, we can use cURL or our browser with the URL:

http://localhost:4567/users

The next steps are on you. Implement a front-end with Javascript or consuming the services with a mobile app or… whatever you prefer.

See you.

Quick REST demo with Spark

One thought on “Quick REST demo with Spark

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.