Endpoint: HTTP Get

Our first task is simple: If client access SERVER_URL/authors, it will Get a list of authors. Note that SERVER_URL for now is port 7000 on localhost (http://127.0.0.1:7000/) on your computer.

Here is a code:

public static void main(String[] args) {
// set port number and ignite SparkJava
final int PORT_NUM = 7000;
port(PORT_NUM);
get("/", (req, res) -> "Welcome to MyBooksApp");
get("/authors", (req, res) -> {
String results = new Gson().toJson(new Sql2oAuthorDao(getSql2o()).listAll());
res.type("application/json");
return results;
});
}

Each of the above get function calls defines an api endpoint and is called a route.

info

We will use JSON to transfer data between server and client so "the list of authors" will be a JSON Array.

Get set up!

In addition to starting the (local) server we must the MyBooksApp database and the Authors table, specifically, into our author Data Access Object (i.e. AuthorsDao). That is what we did with:

new Sql2oAuthorDao(getSql2o()).listAll()

Note the call to the helper method getSql2o() to get a new instance of Sql2o to the MyBooksApp database.

Here is the implemetation of getSql2o helper method:

private static Sql2o getSql2o() {
final String URI = "jdbc:sqlite:./MyBooksApp.db";
final String USERNAME = "";
final String PASSWORD = "";
return new Sql2o(URI, USERNAME, PASSWORD);
}

We pass the Sql2o object that this helper method returns to the constructor of the Sql2oAuthorDao class.

caution

In order for the above code to work, the MybooksApp database should exist with a valid Authors table in it (and ideally some rows in the table). For more info on how to create a databse and tables, and insert rows into them, refer to the previous readings under Persistence with Databases section.

Once we have the list of authors from the Authors table, we use the toJson method of Gson to convert them into a JSON array of authors and store them into a string. We covered JSON and Gson here.

Next, we need to set the content type of our http response as well as the response status. Since we are returning the data in JSON format, we set it accordingly, and we also set the status to 200 to indicate success:

res.type("application/json");
res.status(200);

Eventually, we return the results.

HTTP content type and statuses

You can see a full list of different MIME types here. Also, the following table shows different http status codes and their meaning:

StatusMeaning
200 (OK)This is the standard response for successful HTTP requests.
201 (CREATED)This is the standard response for an HTTP request that resulted in an item being successfully created.
204 (NO CONTENT)This is the standard response for successful HTTP requests, where nothing is being returned in the response body.
400 (BAD REQUEST)The request cannot be processed because of bad request syntax, excessive size, or another client error.
403 (FORBIDDEN)The client does not have permission to access this resource.
404 (NOT FOUND)The resource could not be found at this time. It is possible it was deleted, or does not exist yet.
500 (INTERNAL SERVER ERROR)The generic answer for an unexpected failure if there is no more specific information available.

If you run the application and point your browser to http://127.0.0.1:7000/authors, you must see a list of authors in JSON array format, something like:

[{id: 1, name: "George Orwell", numOfBooks: 13, nationality: "British"}, {id: 2, name: "Franz Kafka", numOfBooks: 16, nationality: "Bohemian"}]
tip

You can use a browser extension like JSON Formatter to prettify the output into a more readable one.