์ถ์ฒ
https://inf.run/XKQg
@GetMapping("/api/v1/calc")
public CalcResponse getCalcResults(
@RequestParam int num1,
@RequestParam int num2) {
// ..
}
@RequestParam
์ด๋
ธํ
์ด์
์ ์ฌ์ฉํ๋ฉด, HTTP ์์ฒญ ํ๋ผ๋ฏธํฐ์ ์ด๋ฆ์ผ๋ก ๋ฐ์ธ๋ฉํ์ฌ ๊ทธ ๊ฐ์ ๋ณ์์ ์ ์ฅํ๋ค.
(ํ๋ผ๋ฏธํฐ์ ์ด๋ฆ๊ณผ ๋ณ์์ด๋ฆ์ด ๋ค๋ฅด๋ค๋ฉด, @RequestParam
์ value
๋ฅผ ์์ฑํด์ผ ํ๋ค.)
๋ค๋ง, ์ฌ๋ฌ ๊ฐ์ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ์ ๋ @RequestParam
์ ์ฌ์ฉํ๋ฉด ๊ฐ๋
์ฑ์ ํด์น ์ ์์ผ๋ฏ๋ก Dto
๋ก ๋ฐ์์ค๋๋ก ํ๋ค.
// Request Dto
public record CalcRequest(int num1, int num2) {
}
// Response Dto
public record CalcResponse(int add, int minus, int mul) {
}
Dto
๋ ์ด๋ฆ ๊ทธ๋๋ก ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๋ ๊ฐ์ฒด์ด๋ค.
Controller์ API method์ ํ๋ผ๋ฏธํฐ๋ก Dto
๋ฅผ ์ฌ์ฉํ๋ฉด, ์คํ๋ง์ด ์๋์ผ๋ก Dto
์ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ๋ฅผ ๋ฐ์ธ๋ฉํ๋ค.
๋ํ, ์ฐ์ฐ ๊ฒฐ๊ณผ๋ฅผ Dto
์ ๋ด์ ๋ฆฌํดํ๋ฉด, ์คํ๋ง์ด ํด๋น ๊ฐ์ฒด๋ฅผ JSON์ผ๋ก ์๋ ๋ณํํ์ฌ ์๋ต์ ํด์ค๋ค.
์ฌ๊ธฐ์ class
๋์ ์ ์ ์ฝ๋๋ก ๋ช
ํํ ์๋๋ฅผ ํํํ ์ ์๋ record
๋ฅผ ์ฌ์ฉํ๋ค.
record
ํน์ง์ ๋ค์๊ณผ ๊ฐ๋ค.
private final
๋ก ์ ์ธ๋๋ค. (๋ถ๋ณ)public
์์ฑ์๋ฅผ ์๋์ผ๋ก ์์ฑํ๋ค.equals
, hashcode
, toString
์ ์๋์ผ๋ก ์์ฑํ๋ค.import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
@GetMapping("/api/v1/calc")
public CalcResponse getCalcResults(CalcRequest request) {
int num1 = request.num1();
int num2 = request.num2();
return new CalcResponse(num1 + num2, num1 - num2, num1 * num2);
}
}
๊ณผ๊ฑฐ์๋ ๊ธฐ๋ณธ ๋ ์ง ํ์
์ธ Date
ํด๋์ค, Calendar
ํด๋์ค๋ฅผ ์ฌ์ฉํ์ง๋ง, Java 8๋ถํฐ LocalDate
ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ค.
LocalDate
์ ์ฃผ์ ํน์ง์ ๋ค์๊ณผ ๊ฐ๋ค.
yyyy-MM-dd
)๋ฅผ ๋ํ๋ธ๋ค.import java.time.DayOfWeek;
import java.time.LocalDate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DayController {
@GetMapping("/api/v1/day-of-the-week")
public DayResponse getDay(@RequestParam("date") LocalDate date) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
return new DayResponse(dayOfWeek.toString());
}
}
์ด๋ฒ์๋ @RequestParam
์ด๋
ธํ
์ด์
๊ณผ LocalDate
๋ฅผ ์ฌ์ฉํ์ฌ ์ฟผ๋ฆฌ ํ๋ผ๋ฏธํฐ ๊ฐ์ ๋ฐ์ธ๋ฉํ๋ค.
๋ํ, ์์ผ์ ๋ฆฌํดํด์ผ ํ๋ฏ๋ก LocalDate
ํด๋์ค์ getDayOfWeek()
๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ค.
POST
API๋ฅผ ๋ง๋ค๊ธฐ ์ํด @RequestBody
์ด๋
ธํ
์ด์
์ ์ฌ์ฉํด์ผ ํ๋ค.
@RequestBody
๋ ์คํ๋ง์์ ์์ฒญ ๋ณธ๋ฌธ์ ์๋ฐ ๊ฐ์ฒด๋ก ๋งคํํ๋ ์ด๋
ธํ
์ด์
์ด๋ฉฐ, ๋ณธ๋ฌธ ๋ฐ์ดํฐ๊ฐ ์์ผ๋ฉด 400 Bad Request
์ค๋ฅ๋ฅผ ๋ฐ์ํ๋ค.
public record SumRequest(List<Integer> numbers) {
}
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CalcController {
@PostMapping("/api/v1/sum")
public int sumNumbers(@RequestBody SumRequest request) {
return request.numbers().stream()
.mapToInt(number -> number)
.sum();
}
}
Request Dto์ ๋ฉค๋ฒ ๋ณ์๋ฅผ List<Integer>
๋ก ์ง์ ํ์ฌ JSON ๋ฐฐ์ด์ ๋งคํํ๊ณ , ์คํธ๋ฆผ์ ์ฌ์ฉํ์ฌ ๋ฆฌ์คํธ ์์์ ํฉ์ ๊ณ์ฐํ์ฌ ๋ฆฌํดํ๋๋ก ํ๋ค.