Gson
We want to return a list of (sample) courses as the response to the request directed at the endpoint /api/courses
, in JSON format. This choice is in-line with what SIS API does, and for that matter with what most APIs do.
To do so, we will use Gson, a Java library (developed at Google) to convert Java Objects into JSON and back. Another popular choice is Jackson. Programs like Gson and Jackson are called Object Mapper. To use Gson, add the following line to the dependencies of your project (build.gradle
):
implementation 'com.google.code.gson:gson:2.8.6'
Open the Gradle tool window and refresh the Gradle project. Then, update ApiServer.java
as follows:
public class ApiServer {
public static void main(String[] args) {
List<Course> courses = new ArrayList<>();
courses.add(new Course("EN.500.112","GATEWAY COMPUTING: JAVA"));
courses.add(new Course("EN.601.220","INTERMEDIATE PROGRAMMING"));
courses.add(new Course("EN.601.226","DATA STRUCTURES"));
courses.add(new Course("EN.601.229","COMPUTER SYSTEM FUNDAMENTALS"));
courses.add(new Course("EN.601.231","AUTOMATA and COMPUTATION THEORY"));
+ Gson gson = new Gson();
- get("/api/courses", (req, res) -> courses);
+ get("/api/courses", (req, res) -> courses, gson::toJson);
}
}
Stop the server and run it again. Then, go to Postman and send a Get request to http://localhost:4567/api/courses to get the list of sample courses:
Notice the result is in JSON format but Postman did not recognize (and thus didn't pretty print) it. Postman thinks the data it received is in HTML format. Let's fix this! Change the following statement:
get("/api/courses", (req, res) -> courses, gson::toJson);
to
get("/api/courses", (req, res) -> {
res.type("application/json");
return courses;
}, gson::toJson);
Stop the server and run it again. Then, go to Postman and send a Get request to http://localhost:4567/api/courses to get the list of sample courses in JSON format, and pretty-printed:
Notice in the callback function to handle Get request, the res
parameter is Spark's response object. It has several methods that help you to prepare the "response" which will be sent to the client. For example, I used res.type
to set the response content type to "application/json". That's how Postman finally recognized the data it received was in JSON format.
Another commonly used response method is res.status(200)
to set the response status code to 200
(or other status codes as described on MDN Web Docs). The 200
is the standard response for successful HTTP requests. Spark sets it by default (that's why I didn't set it manually).