Implementing a Web API with Spark
CS – Advanced Programming Concepts
Spark Overview
Spark Java
A Simple Spark Server
import spark.Spark;��public class SimpleHelloBYUServer {� public static void main(String[] args) {� Spark.get("/hello", (req, res) -> "Hello BYU!");� }�}
-------------
Alternative Handler Implementation: Method Reference
import spark.Spark;
import spark.Request;
import spark.Response;��public class SimpleHelloBYUServer {
� public static void main(String[] args) {� Spark.get("/hello", SimpleHelloBYUServer::handleHello);� }
private static Object handleHello(Request req, Response res) {
return "Hello BYU!";
}�}
Alternative Handler Implementation: Route Class
import spark.Spark;
import spark.Request;
import spark.Response;
import spark.Route��public class SimpleHelloBYUServer {
� public static void main(String[] args) {� Spark.get("/hello", new HelloHandler());� }
}
class HelloHandler implements Route {
public Object handle(Request req, Response res) {
return "Hello BYU!";
}
}
Specifying the Port from the Command Line
import spark.Spark;��public class HelloBYUServer {� public static void main(String[] args) {� try {� int port = Integer.parseInt(args[0]);� Spark.port(port);�� createRoutes();�� Spark.awaitInitialization();� System.out.println("Listening on port " + port);� } catch(ArrayIndexOutOfBoundsException | NumberFormatException ex) {� System.err.println("Specify the port number as a command line parameter");� }� }�� private static void createRoutes() {� Spark.get("/hello", (req, res) -> "Hello BYU!");� }�}
�
�
Spark Routes
Spark Routes
get("/", (request, response) -> {
// Show something
});
post("/", (request, response) -> {
// Create something
});
put("/", (request, response) -> {
// Update something
});
delete("/", (request, response) -> {
// Delete something
});
Routes are matched in the order they are defined. The first route that matches the request is invoked.
Named Parameters
// matches "GET /hello/foo" and "GET /hello/bar" get("/hello/:name", (request, response) -> {
return "Hello: " + request.params(":name");
});
Wildcard Parameters
// matches "GET /say/hello/to/world”
// request.splat()[0] is 'hello' and
// request.splat()[1] 'world’
get("/say/*/to/*", (request, response) -> {
return "Number of splat parameters: " +
request.splat().length;
});
Useful Request and Response Methods
Request
Response
Serving Static Files
Serving Static Files / Web Applications
import spark.Spark;
�public class StaticFileServer {� public static void main(String[] args) {� try {� int port = Integer.parseInt(args[0]);� Spark.port(port);�� // Must be done before mapping routes� Spark.staticFiles.location("/public");�� createRoutes();�� Spark.awaitInitialization();� System.out.println("Listening on port " + port);� } catch(ArrayIndexOutOfBoundsException | NumberFormatException ex) {� System.err.println("Specify the port number as a command line parameter");� }� }�� private static void createRoutes() {� Spark.get("/hello", (req, res) -> "Hello BYU!");� }�}�
Serving Static Files (cont.)
Overriding the Default Not Found Page
import spark.Spark;
�public class CustomNotFoundStaticFileServer {� public static void main(String[] args) {� try {� int port = Integer.parseInt(args[0]);� Spark.port(port);�� // Must be done before mapping routes� Spark.staticFiles.location("/public");
Spark.notFound("<html><body>My custom 404 page</body></html>");
…
Overriding the Default Not Found Page with Content From a File
Spark.notFound((req, res) -> {� res.type("text/html");� return readFromClasspathDirectory("/public/404.html");�});
private static String readFromClasspathDirectory(String file) {� try {� InputStream inputStream =
CustomNotFoundStaticFileServer2.class.getResourceAsStream(file);� BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));�� StringBuilder content = new StringBuilder();� String line;� while ((line = reader.readLine()) != null) {� content.append(line).append("\n");� }�� return content.toString();� } catch (IOException e) {� return file + " file not found.";� }�}�
Filters
Filters
before((request, response) -> {
boolean authenticated;
// ... check if authenticated
if (!authenticated) {
halt(401, "You are not welcome here");
}
});
before("/protected/*", (request, response) -> {…});
Before Filter Example
import spark.Spark;��public class BeforeFilterExample {� public static void main(String[] args) {� try {� int port = Integer.parseInt(args[0]);� Spark.port(port);�� createRoutes();�� Spark.awaitInitialization();� System.out.println("Listening on port " + port);� } catch(ArrayIndexOutOfBoundsException | NumberFormatException ex) {� System.err.println("Specify the port number as a command line parameter");� }� }�� private static void createRoutes() {� Spark.before((req, res) -> System.out.println(
"Executing route: " + req.pathInfo()));
� Spark.get("/hello", (req, res) -> "Hello BYU!");� }�}
Installation
Making Spark Java Available to Your Project
Three Ways:
<dependency>
<groupId>com.sparkjava</groupId>
<artifactId>spark-core</artifactId>
<version>2.9.4</version>
</dependency>
implementation group: 'com.sparkjava', name: 'spark-core', version: '2.9.4'