[Spring] Spring์—์„œ REST API

SHINYEJIยท2023๋…„ 10์›” 27์ผ
0

Back-End

๋ชฉ๋ก ๋ณด๊ธฐ
7/24

REST API ์„ค์ •

pom.xml์— Jackson Library ์ถ”๊ฐ€

  • ์ž๋ฐ” ๊ฐ์ฒด๋ฅผ JSON์œผ๋กœ ๋ฐ”๊พธ๊ฑฐ๋‚˜ JSON์„ ์ž๋ฐ” ๊ฐ์ฒด๋กœ ๋ฐ”๊ฟ€ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋‹ค.
<!-- ์ž๋ฐ”๊ฐ์ฒด <==> JSON -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson-databind-version}</version>
</dependency>

REST์˜ Annotation ์‚ฌ์šฉํ•˜๊ธฐ

๐Ÿ”ด @RestController

  • @RestController๋Š” @Controller์— @ResponseBody๊ฐ€ ์ถ”๊ฐ€๋œ ๊ฒƒ์ด๋‹ค.

๐Ÿ”ด @ResponseBody

  • JSP ๊ฐ™์€ ๋ทฐ๋กœ ์ „๋‹ฌ๋˜๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๋ฐ์ดํ„ฐ ์ž์ฒด๋ฅผ ์ถ”์ถœํ•œ๋‹ค (json์ด๋‚˜ xmlํ˜•์‹์œผ๋กœ ๋ฐ์ดํ„ฐ ์ž์ฒด๋ฅผ ์ „๋‹ฌํ•˜๊ณ  ์‹ถ์„ ๋•Œ)

๐Ÿ”ด @PathVariable

  • URL ๊ฒฝ๋กœ์— ์žˆ๋Š” ๊ฐ’์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ถ”์ถœํ•œ๋‹ค.
public ResponseEntity<?> userInfo(@PathVariable("userid") String userId) {

๐Ÿ”ด @RequestBody

  • JSON ๋ฐ์ดํ„ฐ๋ฅผ ์›ํ•˜๋Š” ํƒ€์ž…์œผ๋กœ ๋ฐ”์ธ๋”ฉํ•œ๋‹ค.
public ResponseEntity<?> userRegister(@RequestBody MemberDto memberDto) {

๐Ÿ”ด @CrossOrigin


Rest API ์‚ฌ์šฉ ์‹œ Status๋ฅผ ํ•จ๊ป˜ ๋ณด๋‚ด๊ธฐ

  • return type์„ ์ œ๋„ค๋ฆญ์œผ๋กœ "?"๋ผ๋Š” ์™€์ผ๋“œ ์นด๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ResponseEntity<?>์„ ๋ฆฌํ„ดํ•˜๋ฉด ํ˜•๋ณ€ํ™˜ ํ•  ํ•„์š” ์—†์ด status๊ฐ€ ํฌํ•จ๋œ ๊ฐ์ฒด๋ฅผ responseํ•  ์ˆ˜ ์žˆ๋‹ค.

    ResponseEntity์„ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ์ง€ ์•Š์œผ๋ฉด Map์„ ๋งŒ๋“ค์–ด์„œ ๋ฐ์ดํ„ฐ์— ์ƒํƒœ ์ฝ”๋“œ๋ฅผ ์ถ”๊ฐ€ ํ•  ์ˆ˜ ์žˆ์ง€๋งŒ ๋ณต์žกํ•˜๊ธฐ ๋•Œ๋ฌธ์— ResponseEntity์„ ์‚ฌ์šฉํ•˜์ž.
    ๊ทธ๋Ÿฌ๋‚˜, ResponseEntity<?>๊ฐ€ ๋งŽ์€ ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์“ฐ๋Š”๊ฒƒ์ด ์ข‹๋‹ค๊ณ  ํ•œ๋‹ค.
    ๋˜ํ•œ, ๊ฒฝ์šฐ์— ๋”ฐ๋ผ Error String๋ฅผ ๋ณด๋‚ผ ์ˆ˜๋„, ๋ฐ์ดํ„ฐ ๊ฐ์ฒด๋ฅผ ๋ณด๋‚ผ ์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ œ๋„ค๋ฆญ์— ํŠน์ • ํƒ€์ž…์„ ์ง€์ •ํ•˜๊ธฐ ๋ณด๋‹จ ์™€์ผ๋“œ ์นด๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์„ ๊ถŒ์žฅํ•œ๋‹ค.

	@PostMapping
	@ResponseBody
	/* application/JSON */
	public ResponseEntity<Void> registBook(@RequestBody Book book){
		
		bookService.registBook(book);
		
		return ResponseEntity.status(HttpStatus.CREATED).build();
	}

0๊ฐœ์˜ ๋Œ“๊ธ€