Building a RESTful Web Service

김동호·2022년 7월 30일
0

목표

https://spring.io/guides/gs/rest-service/ 를 참고하여 간단한 RESTful 웹 서비스 만들어봄으로서, Spring을 사용하여 RESTful하게 웹 서비스를 개발한다는 것을 이해하기.

What You Will Build

http://localhost:8080/greeting 에 GET 요청을 보냈을 때 응답을 받는 서비스 build.

응답은 아래와 같은 JSON 방식으로 받는다.

{"id":1, "content":"Hello, World!"}

다음과 같이 쿼리 파라미터로 커스터마이징 할 수도 있다.
http://localhost:8080/greeting?name=User

{"id":1,"content":"Hello, User!"}

Spring Setting

[https://start.spring.io] 에 접속하여 알맞게 설정한다.
Dependecies에 Spring Web을 추가하자.

Create a Resource Representation Class

응답에 표현이 될 Resource Class를 만들어보자.
여기서는 간단히 long idString content가 필드로 이루어져있다.

요청에 의한 응답으로 아래의 객체에 값들이 들어가고, 그 객체가 응답 메시지 body부에 그대로 반환된다. 그러면 Spring-web-starter dependecy에 포함되어 있는 Jackson JSON 라이브러리에 의해 JSON 형식으로 body부에 뿌려지게 된다.

src/main/java/com/example/restservice/Greeting.java

package com.example.restservice;

public 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;
	}
}

Create a Resource Controller

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 static final String template = "Hello, %s!";
	private final AtomicLong counter = new AtomicLong();

	@GetMapping("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

/greeting에 Get 방식으로 요청을 응답하는 메소드이다.

@RequestParm 어노테이션을 이용해 쿼리 파라미터를 받을 수 있도록 설정했다.
그 안에 속성으로는 value를 통해 name에 담겨진 값을 받고, 아무 값이 입력이 되지 않아도 defaultValue로서 기본값을 설정해주었다.

Test the Service

이제 서버를 실행시키고 http://localhost:8080/greeting으로 접속하면 아래와 같은 창을 볼 수 있다.
{"id":1,"content":"Hello, World!"}

이를 응용하여, 쿼리 파라미터를 이용하여 http://localhost:8080/greeting?name=userName 으로 입력하여 접속하면

{"id":2,"content":"Hello, userName!"} 으로 값이 바뀌는 것을 확인할 수 있다.


결론

결국 RESTful하게 웹 서비스를 만든다는 것은, Controller를 통해 객체를 반환하는 것으로 이해하면 되겠다.

profile
newBlog == https://kdkdhoho.github.io

0개의 댓글