Let's make the service return some students.
Start H2 if you haven't already.
Add a StudentDAO
field named dao
to the Server
class. Initialise the field with an instance of StudentJdbiDAO
(use the factory).
Change the Hello World
code in the constructor to:
get("/api/students", ctx -> dao.getStudents());
Stop and run the server again.
Reload the page in the browser. Append api/products
to the URI.
You should see some students. Jooby is using the toString
method to display the students.
REST APIs were covered in lecture 8. Recall from that lecture that an operation is made up of:
A path that represents a unique resource, or a collection of resources. In this case /api/students
refers to a collection of students.
An HTTP method that defines what the operation will do to the resource. In this case GET
.
So this route (that is what Jooby calls these things) will return the collection of students.
Add the following to the constructor (below what is already here).
get("/api/students/{id}", ctx -> { Integer id = ctx.path("id").intValue(); Student student = dao.getByID(id); if(student == null) { // no product with that ID found, so return a 404/Not Found error return ctx.send(StatusCode.NOT_FOUND); } else { return product; } });
The variable ctx
holds the HTTP context which includes the request details. In this case we are extracting a path parameter named id
out of the context.
If a non-existent ID is provided then the service should return a 404/Not Found
response rather than a null.
Stop and run. Append a student ID for a student that exists in your database to the end of the URI in the browser. You should see the details for a that student appear in the browser.
The ID that you added to the end of the URI becomes the id
path parameter.