Search Courses

Here is another GET request.

Read Courses (filter by title)
HTTP MethodGET
API Endpoint/api/courses
Request Path Parameter
Request Query Parametertitle
Request Body
Response BodyJSON array of notes
Response Status200

For this one, we expect a client to use the same endpoint as the one for getting all the courses but optionally provide a title as a query parameter.

Here is a unit test for testing this API endpoint:

@Test
public void getCoursesGivenTitle() throws UnirestException {
  final String TITLE = "data";
  final String URL = BASE_URL + "/api/courses?title=" + TITLE;
  HttpResponse<JsonNode> jsonResponse = Unirest.get(URL).asJson();
  assertEquals(200, jsonResponse.getStatus());
  assertNotEquals(0, jsonResponse.getBody().getArray().length());
}

Notice the underlying assumption in the test is that there is at least one course which its title include the word "data".

Here is a Postman request corresponding to the above test:

To implement the route handler, we update the handler for api/courses as follows:

get("/api/courses", (req, res) -> {
  try {
-   List<Course> courses = courseDao.readAll();
+   String title = req.queryParams("title");
+   List<Course> courses;
+   if (title != null) {
+     courses = courseDao.readAll(title);
+   } else {
+     courses = courseDao.readAll();
+   }
    return gson.toJson(courses);
  } catch (DaoException ex) {
    throw new ApiError(ex.getMessage(), 500);
  }
});

Notice how I use the req.queryParams method to get the title query parameters (as opposed to using req.params for getting path parameters).

If you want to identify a resource, you should use "path parameter". But if you want to sort or filter items, then you should use query parameter. Source: When Should You Use Path Variable and Query Parameter?

If you have not yet implemented the overloaded Sql2oCourseDao.readAll method, your tests won't pass. But they should pass as soon as you have that implementation in place.