Start learning free

LESSON 13 OF 173 · BACKEND: YOUR FIRST API

Your First Route in Java

Practice

A web server is a program that waits for requests and answers them. A browser, or any other program, sends a request: a method, like GET ("give me"), and a path, like / or /products. The server sends back a response: a status code that says how it went, and a body.

In Spring Boot, the class marked @SpringBootApplication is your app, and a class marked @RestController holds its routes. A route teaches the app to answer a path. A route is an annotation, like @GetMapping("/hello"), on the line right above a method:

@GetMapping("/hello")
String hello() {
    return "Hi there!";
}

When a GET request for /hello arrives, Spring calls hello and sends back whatever it returns, with the status 200, which means OK. A path that no route matches gets 404 Not Found, with Spring's own HTML error page.

Your app must answer:

GET /          →  200  Welcome to the shop!
GET /products  →  404  (an HTML error page)

Your task: the app and the empty ShopController class are already there for you. Inside ShopController, add a route for the path / with a method named home that returns the String "Welcome to the shop!".


Assignment
Follow the Coding Tutorial to write the shop's first route, GET /, and its method home.


Hint
The annotation goes on the line right above the method, with the path as a string in its parentheses. The method's first line says it returns a String, and the return line inside its braces ends with a semicolon.


STEP 1 OF 3
    Ctrl + Enter to check

    Shop First Route 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