In the first Spring Boot tutorial Spring Boot tutorial - first simple application we have created very simple application that starts application server. It even did not respond with human understandable content. Now we will create simplest Rest service. We will extend the application created in the first tutorial Spring Boot tutorial - first simple application.

To create new Rest service is very easy. We need to add couple of annotations - one on class and another on method. Let's we add new class to the project:

package com.zerotoherodev.tutorial.springboot.services;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FirstRestService {
    @GetMapping("/")
    public String defaultGetResponse() {
        return "Hello from first Rest service!";
    }
}

Now run the code as is described in the previous tutorial and go to the URL http://localhost:8080/. You will see response from the server:

Hello from first Rest service!

Let's analyze our newly added class. It is very simple class with one method returning String result. What is added it is annotation @RestController. This annotation tells Spring framework to treat it as Rest service. Another annotation is @GetMapping("/"). GetMapping annotation tells Spring framework, that it is endpoint that is accessed with GET HTTP method. The URL inside the annotation tells that it is default service endpoint for the application.

Let's add another method to the class FirstRestService that publishes another Rest service endpoint:

package com.zerotoherodev.tutorial.springboot.services;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FirstRestService {
    @GetMapping("/")
    public String defaultGetResponse() {
        return "Hello from first Rest service!";
    }

    @GetMapping("/anotherEndpoint")
    public String anotherEndpoint() {
        return "This is second endpoint!";
    }
}

Now run the application and access the URL http://localhost:8080/anotherEndpoint . You will see in your browser text 

This is second endpoint!

Now our Rest service has two endpoints.

Comments powered by CComment