REST API

์ฝœ๋ผ๋ง˜ยท2023๋…„ 7์›” 10์ผ
0

Spring

๋ชฉ๋ก ๋ณด๊ธฐ
12/14
post-thumbnail

๐Ÿ€ REST

  • HTTP URI๋กœ ํ•ด๋‹น ์ž์›์„ ์‹๋ณ„ํ•˜๊ณ  HTTP method๋กœ ํ•ด๋‹น ์ž์›์— ๋Œ€ํ•œ CRUD๋ฅผ ๊ตฌ๋ถ„ํ•˜์—ฌ ์ž์›๋งŒ ์‘๋‹ตํ•˜๋Š” ๋ฐฉ์‹
  • HTML ๋ทฐ ํŽ˜์ด์ง€๊ฐ€ ์•„๋‹Œ ์ž์›๋งŒ ์‘๋‹ตํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์›น ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์•„๋‹Œ ํ”„๋กœ๊ทธ๋žจ์—์„œ๋„ ์„œ๋ฒ„๋ฅผ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์žฅ์ ์ด ์žˆ๋‹ค
  • Create, Insert(POST method) POST:/employee - ์ƒˆ ์‚ฌ์›์„ ์ถ”๊ฐ€ํ•œ๋‹ค
  • Read, Select(GET method) GET:/employee/105 - 105๋ฒˆ ์‚ฌ์›์„ ์กฐํšŒํ•œ๋‹ค
  • Update (PUT method) PUT:/employee/183 - 183๋ฒˆ ์‚ฌ์›์„ ์ˆ˜์ •ํ•œ๋‹ค
  • Delete (DELETE method) DELETE:/employee/170 - 170๋ฒˆ ์‚ฌ์›์„ ์‚ญ์ œํ•œ๋‹ค

๐Ÿ€ Spring REST

  • @RestController : ํ•ด๋‹น ํด๋ž˜์Šค๊ฐ€ RestController์ž„์„ ํ‘œ์‹œ
  • @ResponseBody : ํ•ด๋‹น ๋ฉ”์„œ๋“œ๊ฐ€ ๋ทฐ ํŽ˜์ด์ง€ ๋Œ€์‹  ๋ฐ์ดํ„ฐ๋ฅผ ์‘๋‹ตํ•œ๋‹ค๋Š” ๊ฒƒ์„ ํ‘œ์‹œ
  • @RequestBody : ์š”์ฒญ์— ์‹ค๋ ค์˜จ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ”์ธ๋”ฉํ•ด์ฃผ๋Š” ์–ด๋…ธํ…Œ์ด์…˜
  • @PathVariable : ์š”์ฒญ URI์˜ ์ผ๋ถ€๋ถ„์„ ๋ณ€์ˆ˜์˜ ๊ฐ’์œผ๋กœ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค(์ผ๋ฐ˜ ์ปจํŠธ๋กค๋Ÿฌ์—์„œ๋„ ์‚ฌ์šฉ ๊ฐ€๋Šฅ)

๐Ÿ€ @RestController

  • ์ผ๋ฐ˜ ์ปจํŠธ๋กค๋Ÿฌ์™€ ๋‹ค๋ฅด๊ฒŒ ๋‹ค์Œ ๋ทฐ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋Œ€์‹  ๋ฐ์ดํ„ฐ๋ฅผ ์‘๋‹ตํ•œ๋‹ค
  • ์ปจํŠธ๋กค๋Ÿฌ ๋‚ด๋ถ€ ๋ฉ”์„œ๋“œ์˜ ๋ฆฌํ„ดํƒ€์ž…์€ ๋ทฐ๋ฅผ ์ฐพ์•„๊ฐ€๋Š” ๋ฐฉ์‹์ด ์•„๋‹ˆ๋ผ ์‚ฌ์šฉ์ž์—๊ฒŒ ์‘๋‹ตํ•  ๋ฐ์ดํ„ฐ์˜ ํƒ€์ž…์„ ์˜๋ฏธํ•œ๋‹ค
  • ์ฃผ๋กœ JSON๋ฐฉ์‹ ๋˜๋Š” XMLํ˜•์‹์œผ๋กœ ์‘๋‹ตํ•˜๊ฒŒ ๋œ๋‹ค

๐Ÿ€ jackson-databind์™€ jackson-dataformat-xml

  • @RestController์—์„œ ์ž๋ฐ”๋นˆ ๊ฐ์ฒด๋ฅผ ๋ฆฌํ„ดํ•˜๋ฉด ์•Œ์•„์„œ JSON(๋˜๋Š” XML)ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•ด ์‘๋‹ตํ•ด์ฃผ๋Š” ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
  • jackson-databind์™€ jackson-dataformat-xml์˜ Maven์„ ๋ณต์‚ฌํ•˜์—ฌ pom.xml์— ๋ถ™์—ฌ๋„ฃ๊ธฐ(์•„๋ž˜ ๋‚ด์šฉ ๋ณต์‚ฌํ•ด๋„ ๋จ)
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.dataformat</groupId>
	<artifactId>jackson-dataformat-xml</artifactId>
	<version>2.15.2</version>
</dependency>

๐ŸŒผ RestController์—์„œ ์‚ฌ์šฉํ•˜๊ธฐ

๐ŸŒฑ jsonํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ

@RequestMapping("/restful")
@Log4j
@RestController
public class RestSampleController {
	@GetMapping(value="/employee/json", produces = MediaType.APPLICATION_JSON_VALUE)
	public Employee emp1() {
		Employee e = new Employee();
		e.setFirst_name("์ฒ ์ˆ˜");
		e.setLast_name("๊น€");
		e.setSalary(5000);
		return e;
	}
}

๐Ÿ“บ ์ถœ๋ ฅ ๊ฒฐ๊ณผ >>

๐ŸŒฑ xmlํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ

@RequestMapping("/restful")
@Log4j
@RestController
public class RestSampleController {
	@GetMapping(value="/employee/xml", produces = MediaType.APPLICATION_XML_VALUE)
	public Employee emp2() {
		Employee e = new Employee();
		e.setFirst_name("์ฒ ์ˆ˜");
		e.setLast_name("๊น€");
		e.setSalary(5000);
		return e;
	}
}

๐Ÿ“บ ์ถœ๋ ฅ ๊ฒฐ๊ณผ >>


๐Ÿ“š ์ฐธ๊ณ ์ž๋ฃŒ

restful api

profile
์ฝœ๋ผ๋ง˜ ์ฝ”๋”ฉ์ผ๊ธฐ

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