PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   25-09-2021

REST CONTROLLER

The service will handle GET requests for /greeting and return JSON response. Use start.spring.io to create a new Spring Web project.
 
/**
 * /restservice/src/main/java/com/example/App.java 
 */

package com.example.restservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}
... 6 lines
 
! In Spring RESTful web services, HTTP requests are handled by a controller. We will use @RestController annotation to identify the components.
 
/**
 * /restservice/src/main/java/com/example/GreetingController.java 
 */

package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private final AtomicLong counter = new AtomicLong();

    @GetMapping("/greeting")
    public Greeting greeting(
        @RequestParam(value = "name", defaultValue = "World") String name
    ) {

        Long id = counter.incrementAndGet();
        String content = String.format("Hello %s!", name);

        return new Greeting(id, content);
    }
}

class Greeting {

    private final long id;
    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }

}
... 28 lines
 
We can now run the application and test the service. You might want to set a port different from 8080 for you application.
 
./mvnw spring-boot:run
 
http://localhost:9090/greeting
    # {"id":1,"content":"Hello World!"}

http://localhost:9090/greeting?name=User
    # {"id":2,"content":"Hello User!"}
 
# /restservice/src/main/resources/application.properties
server.port=9090
Consumming Rest    (2/2)

CONSUMMING REST

The application will retrive quotes from a RESTful web service. When you request the service URL you receive a JSON document.
 
# https://quoters.apps.pcfone.io/api/random
{
   type: "success",
   value: {
      id: 10,
      quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
   }
}
... 2 lines
 
Start a new Spring Boot Web project.
 
package com.example.consumingrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}
... 3 lines
 
Create a domain class to contain the data that you need. Any property not bound will be ignored.
 
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties (ignoreUnknown = true) // Look Here
public class Quote {
    
    private String type;
    private Value value;

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setValue(Value value) {
        this.value = value;
    }

    public Value getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Quote{type='" + type + "', value=" + value + "}";
    }
}
... 17 lines
 
 
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties (ignoreUnknown = true)
public class Value {

    private Long id;
    private String quote;

    public void setId(Long id) {
        this.id = id;
    }

    public Long getId() {
        return id;
    }

    public void setQuote(String quote) {
        this.quote = quote;
    }

    public String getQuote() {
        return quote;
    }

    @Override
    public String toString() {
        return "Value{id='" + id + "', quote=" + quote + "}";
    }
}
... 17 lines
 
! A RestTemplate will use the Jackson JSON library for incomming data. A CommandLineRunner will run the RestTemplate on startup.
 
package com.example.consumingrest;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) // on startup
        throws Exception {
            return args -> {
                Quote quote = restTemplate.getForObject(
                    "https://quoters.apps.pcfone.io/api/random", Quote.class
                );
                System.out.println(quote);
            };
    }

    @GetMapping("/getquote")
    public String quote() {
        RestTemplate rt = new RestTemplate(); // on request
        Quote quote = rt.getForObject(
            "https://quoters.apps.pcfone.io/api/random", Quote.class
        );
        return quote.toString();
    }

}
... 32 lines
 
Build and test the application in console or browser.
 
./mvnw spring-boot:run
 
#console
2021-09-10 18:37:21.306  INFO 3273 
Quote{type='success', value=Value{id='9', quote='Spring Boot solves ...'}

#browser
localhost:8080/getquote
Quote{type='success', value=Value{id='5', quote='Spring Boot solves ...'}

Questions    
Templates

        A B C D E F
🔔
1/2