Creating an API with fewer lines

Typically, we would write the following few lines to bring up a hello world API with Spark:

1 import static spark.Spark.*;
2
3 public class MyHelloWorld {
4 public static void main(String[] args) {
5 get("/sayhello", (request, response) -> "Hello Reader");
6 }
7 }

That's it! Line one, spark.Spark.*, as indicated in the preceding code snippet, does the magic. By using CURL (curl http://localhost:4567/sayhello), we would visualize the following request and response as output for the previous code:

Request: 
 
GET http://localhost:4567/sayhello 
 
Response: 
 
Hello Reader 
 

As we can see in the preceding snippet, curl hits the application, so the lambda function of Spark.* fires and the client (curl in this case) gets the output of the static lambda function. It's not just a simple hello world API; we can write complex RESTful APIs with Spark as it supports a variety of functions, such as query maps, cookies and sessions, filters, redirects, exception and error handlings, and views and templates.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.200.143