Endpoint: HTTP Post

By design, the POST request method requests that a web server accepts the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form.

In the MyBooksApp, we want to allow the user to enter her/his favorite authors and books into the app. These entries can be made (on a web form) and will be Posted to the server for processing (i.e., getting stored in the database). Let's throw in such an "add" server functionality for authors. We need a new post endpoint:

post("/addauthor", (req, res) -> {
String name = req.queryParams("name");
int numOfBooks = Integer.parseInt(req.queryParams("numOfBooks"));
String nationality = req.queryParams("nationality");
Author a = new Author(name, numOfBooks, nationality);
new Sql2oAuthorDao(getSql2o()).add(a);
res.status(201);
res.type("application/json");
return new Gson().toJson(a.toString());
});

Note how we first parse/read the post query parameters name, numOfBooks and nationality from the received post request. Then, we use them to create a new Author object before sending the object to AuthorDao to insert it into the Authors table for us. Next, we set the response status to 201 (i.e. success - item being successfully created.) Finally, we return the inserted author as a JSON (as a confirmation back to the client).