Skip to content

Endpoint: HTTP Get

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

Here is a starting point:

1
2
3
4
5
6
public static void main(String[] args) {
  Javalin app = Javalin.create().start(7000);
  app.get("/", ctx -> ctx.result("Welcome to CourseReVU App"));
   // TODO: update the code below to actually show a list of courses!
  app.get("/courses", ctx -> ctx.result("List of books"));  
}

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

Get set up!

In addition to starting the (local) server we must (create and) initialize a database with Courses table. We further need to hook that database to our Data Access Objects (i.e. CourseDao here):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public static void main(String[] args) {
  // Preparation!
  Sql2o sql2o = getSql2o();
  createTable(sql2o);
  CourseDao courseDao = getCourseDao(sql2o);
  initData(courseDao);

  Javalin app = startServer();
  app.get("/", ctx -> ctx.result("Welcome to CourseReVU App"));
}

Here is the helper method to start the server:

1
2
3
4
private static Javalin startServer() {
  final int PORT = 7000;
  return Javalin.create().start(PORT);
}

Here is a helper method to create a Sql2o object.

1
2
3
4
5
6
private static Sql2o getSql2o() {
  final String URI = "jdbc:sqlite:./Store.db";
  final String USERNAME = "";
  final String PASSWORD = "";
  return new Sql2o(URI, USERNAME, PASSWORD);
}

We will pass the Sql2o object to this helper method to create the Courses table for us.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
private static void createCoursesTable(Sql2o sql2o) {
  dropCoursesTableIfExists(sql2o);
  String sql = "CREATE TABLE IF NOT EXISTS Courses(" +
                    "id INTEGER PRIMARY KEY," +
                    "name VARCHAR(30) NOT NULL," +
                    "url VARCHAR(100)" +
                ");";
  try (Connection conn = sql2o.open()) {
    conn.createQuery(sql).executeUpdate();
  } 
}

Note the createCoursesTable calls dropCoursesTableIfExists helper method:

1
2
3
4
5
6
private static void dropCoursesTableIfExists(Sql2o sql2o) {
  String sql = "DROP TABLE IF EXISTS Courses;";
  try (Connection conn = sql2o.open()) {
    conn.createQuery(sql).executeUpdate();
  }
}

The following helper method takes in a Sql2o and returns a CourseDao:

1
2
3
private static CourseDao getCourseDao(Sql2o sql2o) {
  return new Sql2oCourseDao(sql2o);
}

Now we can use a CourseDao object to add some sample data:

1
2
3
4
private static void initData(CourseDao courseDao){
  courseDao.add(new Course("oose", "jhu-oose.com"));
  courseDao.add(new Course("Intro os", "jhu-os.com"));
}

courses endpoint

Returning a list of courses is as easy as follows:

1
2
3
4
5
6
app.get("/courses", ctx -> {
  List<Course> courseList = courseDao.findAll();
  ctx.json(courseList);
  ctx.contentType("application/json");
  ctx.status(200);
});
  • ctx.json(courseList); converts the course list into a JSON Array and sends it back as the response.
  • ctx.contentType("application/json"); specifies the type of content that response contains is JSON.
  • ctx.status(200); specifies the process was successful.
Status Meaning
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.

Note

Javalin uses Jackson JSON parser to convert objects to JSON and vise-versa. I recommend using Google's Gson instead.

To add Gson to your project dependency, add the following to dependencies block of build.gradle:

1
implementation 'com.google.code.gson:gson:2.8.6'

To have Javalin use Gson, update the startServer method as follows:

1
2
3
4
5
6
7
private static Javalin startServer() {
  Gson gson = new GsonBuilder().create();
  JavalinJson.setFromJsonMapper(gson::fromJson);
  JavalinJson.setToJsonMapper(gson::toJson);
  final int PORT = 7000;
  return Javalin.create().start(PORT);
}

If you run the application and point your browser to http://127.0.0.1:7000/courses, you must see the following in your browser:

1
[{"id":1,"name":"oose","url":"jhu-oose.com"},{"id":2,"name":"Intro os","url":"jhu-os.com"}]

Tip

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