opencodez

Simple Guide to Spark Framework for Microservices

We have discussed the Microservices concepts like What are Microservices? Why to use it? When to use it? in our previous article ” An Introduction to Microservices Architecture”

Spark Framework for Microservices:

Every modern enterprise application is supported by microservices. These services form the core of the application. To develop these services fast we need an easy and simple framework. In this article, we will have a brief introduction to Spark Framework.

As claimed on the official site for Spark.

Spark x A micro framework for creating web applications in Kotlin and Java 8 with minimal effort

Software used

Using the above tool we will see how Spark Framework can be used to develop some basic services.

Maven Dependencies

xdependenciesx
	xdependencyx
		xgroupIdxcom.sparkjavax/groupIdx
		xartifactIdxspark-corex/artifactIdx
		xversionx2.8.0x/versionx
	x/dependencyx
	xdependencyx
		xgroupIdxcom.google.code.gsonx/groupIdx
		xartifactIdxgsonx/artifactIdx
		xversionx2.8.0x/versionx
	x/dependencyx
x/dependenciesx

The dependency spark-core is what we need to run the complete Spark Web Framework. As we may use some JSON responses during our example so we used GSON library.

Routes

Routes are the main building block in this framework. Each route is made up of 3 basic elements x a verb, a path, and a callback.

The Verb is associated with each of the HTTP methods. These are get, post, put, delete, head, trace, connect, options.

The Path or Route Pattern determines which URI(s) the route should listen to and provide a response.

The Callback is a is a handler function. This function takes two important parameters i.e. request and response objects.

Routes are matched in the order they are defined. The first route that matches the request is invoked. A sample route is like:

get("/", (request, response) -x {
    // Show something
});

Hello World! Service

We will see below a simple and straight forward API developed using Spark Framework. You simply have to provide a main class as below:

import static spark.Spark.get;
import static spark.Spark.port;

public class SparkMain {

	public static void main(String[] args) {

		//configure port
		port(8080);
		
		get("/hello", (req, res)-x"Hello, world!");
		
		get("/hello/:name", (req,res)-x{
            return "Hello, "+ req.params(":name") + "!!";
        });
	}
}

Spark recommends importing the methods statically to ensure good readability.

The first methods configure the Spark embedded server to run on port 8080. The server is automatically started when you do something that requires the server to be started (i.e. declaring a route or setting the port).

The first route is simple and static. The second route is dynamic as it has a placeholder for the name variable. The lambda callback has access to Request and Response objects and can access information out of it.

Testing the Service

Once you run the main class, the Spark server is started and its available on port 8080. You can test the above set routes in the postman.

x

RESTful Service with Spark Framework

We will shortly look on how we can implement a simple RESTful API with this framework.

We have a simple domain object around which we will write the API

@Data
@AllArgsConstructor
public class User {
	private String id;
	private String name;
	private String email;
}

We are not connecting to any database. For our demonstration purpose, we will have some static map that will hold data for us. Below is our service interface:

public interface UserService {
	
	public void addUser(User user);
	
	public void editUser(User user);
	
	public User getUserById(String id);
	
	public void deleteUserById(String id);
	
	public ListxUserx getUsers();
}

1. Add a User

To add a user in our API we will define Spark route as:

post("/users/add", (req,res)-x {
	res.type("application/json");

	User user = new Gson().fromJson(req.body(), User.class);
	userService.addUser(user);

	return new Gson().toJson(user);
});

The postman request is:

2. Get All Users

As we have added users, we need to check if that is available in our system. The get route we have added is:

get("/users", (req,res)-x {
	res.type("application/json");
	return new Gson().toJson(userService.getUsers());
});

This route will return all the users in the system. The postman output:

 3. Edit a User

Editing a user is to replace the user with new information. The route is defined as:

put("/users/edit/:id", (req,res) -x {
	res.type("application/json");
	User ue = new Gson().fromJson(req.body(), User.class);
	
	User searchedUser = userService.getUserById(ue.getId());
	if(searchedUser != null) {
		userService.editUser(ue);
		return new Gson().toJson(ue);
	} else {
		return new Gson().toJson("User not found or error in edit");
	}
	
});

4. Delete a User

In delete route, we are simply removing the element from Map:

delete("/users/delete/:id", (req,res) -x {
	res.type("application/json");
	userService.deleteUserById(req.params(":id"));
	return new Gson().toJson("User deleted");
});

All these routes can be tested in POSTMAN.

Apart from Spark, Spring boot is also very effective framework to build microservices using Java.

Please read : Microservices in Action using Spring Boot

Conclusion

The article takes us through a quick introduction to the Spark framework for rapid web development.

This framework can be used for generating microservices in Java.

You can download the complete code from our GIT Repo

Download Code