Start learning free

LESSON 15 OF 173 · BACKEND: YOUR FIRST API

More Routes in Java

Practice

An API has many paths, and each path has its own method. When a request arrives, Spring compares its path with the path of every @GetMapping, and calls the method whose path matches exactly. So /products/count is not /products: it needs a route of its own.

A route can return any Map, and Spring sends it as a JSON object. For example, a shop could tell its opening hours like this:

@GetMapping("/hours")
Map<String, Object> hours() {
    return Map.of("open", 9, "close", 18);
}

To answer how many items a list has, use products.size() instead of writing the number yourself: the answer stays right when items are added or removed. A path that no route matches, like /contact, gets 404 Not Found: Spring has no method to call.

Your app must answer:

GET /products/count  →  200  {"count": 4}
GET /about           →  200  {"name": "Corner Shop", "currency": "USD"}
GET /contact         →  404  (an HTML error page)
GET /products        →  200  [{"id": 1, "name": "Mug", "price": 12, "category": "kitchen"}, … all 4 products]
GET /                →  200  Welcome to the shop!

Your task: add two routes. GET /products/count, with a method named countProducts, answers the number of products as {"count": …}, computed with products.size(). GET /about, with a method named about, answers the shop's "name", "Corner Shop", and its "currency", "USD".


Assignment
Follow the Coding Tutorial to add the /products/count and /about routes.


Hint
Each new route has the same shape as the others: the @GetMapping annotation with its path, the method line with a new name and the return type Map<String, Object>, then the return. Map.of takes keys and values in turn: key, value, key, value.


STEP 1 OF 6
    Ctrl + Enter to check

    Shop More Routes in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free