Lesson Tuesday

Now that we have learned a little more about JSON, APIs and Postman, let's add some more routes to our App.java, and then throw some requests at it with Postman to test.

Let's build our App.java out in the following way:

src/main/java/App.java
public class App {

   public static void main(String[] args) {
       Sql2oFoodtypeDao foodtypeDao;
       Sql2oRestaurantDao restaurantDao;
       Sql2oReviewDao reviewDao;
       Connection conn;
       Gson gson = new Gson();

       String connectionString = "jdbc:h2:~/jadle.db;INIT=RUNSCRIPT from 'classpath:db/create.sql'";
       Sql2o sql2o = new Sql2o(connectionString, "", "");
       restaurantDao = new Sql2oRestaurantDao(sql2o);
       foodtypeDao = new Sql2oFoodtypeDao(sql2o);
       reviewDao = new Sql2oReviewDao(sql2o);
       conn = sql2o.open();

       post("/restaurants/new", "application/json", (req, res) -> { //accept a request in format JSON
           Restaurant restaurant = gson.fromJson(req.body(), Restaurant.class);//make with GSON
           restaurantDao.add(restaurant);//Do our thing with our DAO
           res.status(201);//everything went well - update the response status code
           res.type("application/json");
           return gson.toJson(restaurant);//send it back to be displayed
       });

       get("/restaurants", "application/json", (req, res) -> { //accept a request in format JSON from an app
           res.type("application/json");
           return gson.toJson(restaurantDao.getAll());//send it back to be displayed
       });

       get("/restaurants/:id", "application/json", (req, res) -> { //accept a request in format JSON from an app
           res.type("application/json");
           int restaurantId = Integer.parseInt(req.params("id"));
           res.type("application/json");
           return gson.toJson(restaurantDao.findById(restaurantId));
       });
   }
}

Great, now we have three routes. This is plenty to test with Postman.

Testing our API with Postman

jadle-postman-1

  1. Let's fire up Postman, and set the HTTP request type to POST, as we need to create a record before we can read it.
  2. Point the URL to localhost:4567/restaurants/new
  3. Select the radio button marked "raw", and the type to " JSON application/json" in the dropdown menu.
  4. Select the Body radio button, and copy in JSON below.
  5. Hit Send!
 {
    "name": "Fish Witch",
    "address": "214 NE Broadway",
    "zipcode": "97232",
    "phone": "503-402-9874",
    "website": "http://www.fishwitch.com",
    "email": "[email protected]"
  }

You should see the a printout added at the bottom simply repeating what you just sent.

Do the above again, but change the JSON you submit a little. Change the name of the restaurant, the zipcode, the phone, the address, and hit Send. Maybe do this one or two more times. Now, we should have 3-4 records in our Database.

Let's retrieve them. Open a new Postman tab, and:

  1. Set the type to GET
  2. Point the URL to...guess what! localhost:4567/restaurants
  3. Hit Send!

You should see a nice list of JSON objects below. I don't know about you, but this is pretty cool!

Next, let's try our last route, to restaurants/id. Open a new Postman tab, and point it to localhost:4567/restaurants/1 via GET. You should see a unique restaurant (the first one) displayed as an output.

Our app successfully accepts JSON inputs, parses them to Java, and stores them in our database for us to retrieve. With what we have just learned, we could make an awesome API that developers and tech folks the world over could query and use in their own projects, just like that. It would just need to be hosted on a server that was accessible to the internet, as opposed to localhost.

While you are at it, try pulling up localhost:4567/restaurants in your browser - you'll see raw JSON data displayed there, which isn't very readable. You can install browser extensions such as JSON Viewer to prettify your browser output of JSON. This does not replace Postman, though: Many APIs require you to send additional information, such as headers, along with requests - browsers can only execute the simplest of GETs.


Example GitHub Repo for Jadle at this stage