Skip to content

Connect to API

Overview

So far, we have used in-memory (no persistence) Data Access Object (i.e. InMemoryCourseDao). This is considered an acceptable approach to start the development process. As progress is made, you are expected to add persistence (e.g. connect to a database to store your application data).

We've already developed persistence mechanism with RESTful API for the CourseReVU App. Let's connect our Web-application to our API! We will be using the HTTP client library Unirest which we have used for Testing Endpoints to connect to the RESTful API we've developed before.

Recall: you need the following dependencies!

1
2
compile group: 'com.mashape.unirest', name: 'unirest-java', version: '1.4.9'
implementation 'com.google.code.gson:gson:2.8.6'

UnirestCourseDao

Here is a simple implementation of our Course Data Access Object to connect to our API.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class UnirestCourseDao implements CourseDao {

  private static Gson gson = new Gson();;
  public final String BASE_URL = "http://127.0.0.1:7000/";

  @Override
  public void add(Course course) {
    try {
      Unirest.post(BASE_URL + "/courses").body(gson.toJson(course)).asJson();
    } catch (UnirestException e) {
      // TODO deal with errors
      e.printStackTrace();
    }
  }

  @Override
  public List<Course> findAll() {
    try {
      HttpResponse<JsonNode> jsonResponse =
          Unirest.get(BASE_URL + "/courses").asJson();
      Course[] courses = gson.fromJson(jsonResponse.getBody().toString(), Course[].class);
      return new ArrayList<>(Arrays.asList(courses));
    } catch (UnirestException e) {
      // TODO deal with errors
      e.printStackTrace();
    }
    return null;
  }
}

BASE_URL

The BASE_URL is where Javalin runs its server locally (by default). You can change it later when you run your RESTful API on an actual server.

Putting it all together!

  • You must first run the Javalin application we've developed before.
  • In WebServer.main, change the implementation of courseDao from InMemoryCourseDao to UnirestCourseDao.
  • Run WebServer and play with the web-application.
  • Try to update course data through Postman and observe the changes in http://localhost:4567/courses.