[Spring] Rest-swagger - GET(1)

์ง„์ฃผยท2022๋…„ 3์›” 18์ผ
0

Spring

๋ชฉ๋ก ๋ณด๊ธฐ
9/29

๐Ÿฅ  ํ™˜๊ฒฝ ์„ค์ • 1 - spring ํŒŒ์ผ ์ƒ์„ฑ

ํด๋” ์„ ํƒ

F1ํด๋ฆญ, Spring Initializr: Create a Maven Project ํด๋ฆญ >>

2.6.4 version ํด๋ฆญ, ๊ณ„์† enter, Jar ํŒŒ์ผ, version 8 ์„ ํƒ

Search for dependencies์—์„œ Spring Web ์„ ํƒ

Selected 1 dependency์—์„œ Enter

Generate into this folder ํด๋ฆญ

Open ํด๋ฆญ

์ƒˆ๋กœ์šด VS code ์ฐฝ ์—ด๋ฆฌ๋ฉด ๋!


๐Ÿง€ ํ™˜๊ฒฝ ์„ค์ • 2 - PORT ๋ฒˆํ˜ธ ์ง€์ •ํ•˜๊ธฐ

์‹คํ–‰์‹œ Oracle๊ณผ Port๋ฒˆํ˜ธ๊ฐ€ ์ถฉ๋Œํ•  ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—

application.properties ์— PORT๋ฅผ ์„ค์ •ํ•ด์ค˜์•ผํ•œ๋‹ค.

์ฐธ๊ณ ํ•ด๋„ ์ข‹์„ ๊ฒƒ ๊ฐ™์€ ์‚ฌ์ดํŠธ : https://central-it.tistory.com/47

server.port=8090 ์ž…๋ ฅํ•˜๋ฉด localhost:8090์œผ๋กœ ํฌํŠธ ๋ฒˆํ˜ธ๊ฐ€ ๋ณ€๊ฒฝ๋œ๋‹ค


๐Ÿฅ— Controller.java

1) getMapping()์„ ํ†ตํ•œ GET ์š”์ฒญ

rest - ํด๋” ๋ช… : controller ์ƒ์„ฑ

controller - ํŒŒ์ผ ๋ช… :Controller.java ์ƒ์„ฑ

@RestController ์ž…๋ ฅ

์ž๋™์œผ๋กœ import org.springframework.web.bind.annotation.RestController; import ๋œ๋‹ค.

@RestController = @Controller + @ResponseBody


@Controller = @Component์™€ ๋™์ผ, bean ๊ฐ์ฒด๋กœ ๋“ฑ๋กํ•œ๋‹ค
@ResponseBody = JSON ๋ฐ์ดํ„ฐ ๋ฐ˜ํ™˜์šฉ Annotation

์ด 2๊ฐ€์ง€ ์—ญํ• ์„ ํ•œ ๋ฒˆ์— ์ˆ˜ํ–‰ํ•˜๋Š” Annotation์ด @RestController์ด๋‹ค.

@RequestMapping("/api/v1")๋ฅผ ์ž…๋ ฅํ•˜๋ฉด localhost:8090/api/vi ๊ฒฝ๋กœ์— ํ•ด๋‹นํ•˜๋Š” ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

@RequestMapping๋Œ€์‹  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Annotation์„ ์•Œ๋ ค์ค€๋‹ค.

GET ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ๋Š”, GetMapping()์„ ์‚ฌ์šฉํ•œ๋‹ค.

์ฝ”๋“œ ์ž‘์„ฑ

์‹คํ–‰ ๊ฒฐ๊ณผ๋Š” chrome์˜ Talend API Tester ์‚ฌ์šฉํ•ด ๋ณผ ๊ฒƒ์ด๋‹ค.


Postman ๋ณด๋‹ค ๊ฐ€๋ฒผ์šด chrome์˜ ํ™•์žฅํ”„๋กœ๊ทธ๋žจ ์‚ฌ์šฉ - Talend API Tester

ํผ์ฆ ๋ชจ์–‘ ํด๋ฆญ, ํ™•์žฅ ํ”„๋กœ๊ทธ๋žจ ๊ด€๋ฆฌ ํด๋ฆญ


์™ผ์ชฝ ํ•˜๋‹จ์˜ Chrome ์›น์Šคํ† ์–ด ์—ด๊ธฐ ํด๋ฆญ

talend API Tester ๊ฒ€์ƒ‰

Chrome์— ์ถ”๊ฐ€ ํด๋ฆญ

ํผ์ฆ๋ชจ์–‘ - Talend API Tester ํด๋ฆญ

Use Talend API Tester ํด๋ฆญ

RestApplication.java๋ฅผ Run(F5)ํ•ด์„œ ์„œ๋ฒ„ ํ‚ค๊ธฐ

http://localhost:8090/api/v1/book ์ ์€ ํ›„, Send ํด๋ฆญ

[๊ฒฐ๊ณผ]

Body์— The Old Man and Sea ์ถœ๋ ฅ๋œ๋‹ค.


2) RequestParam()์„ ํ™œ์šฉํ•œ GET ์š”์ฒญ

  // @RequestParam()์„ ํ™œ์šฉํ•œ GET ์š”์ฒญ
  @GetMapping("/book/req")
  public String getBookWithParam(
    @RequestParam String name,
    @RequestParam String author
  ){
    return String.format("%s ์˜ ์ €์ž %s", name, author);
  }

Controller.java์— ์ฝ”๋“œ ์ถ”๊ฐ€

์•ž์˜ %s๋Š” name, ๋’ค์˜ %s๋Š” author์— ๋งค์นญ๋œ๋‹ค.

QUERY PARAMETERS ํด๋ฆญ, Add query parameter ํด๋ฆญ

name, author ์ž…๋ ฅํ›„, ์„œ๋ฒ„ ์žฌ์‹คํ–‰

Send ํด๋ฆญ ์ „์—,
@GetMapping("/book/req") ์ด๋ฏ€๋กœ book/req? ์ธ์ง€ ํ™•์ธํ•ด์•ผํ•œ๋‹ค.

http://localhost:8090/api/v1/book/req?name=๊น€๋นต๋นต์˜ ์ผ์ƒ&author=๊น€๋นต๋นต ์ธ์ง€ ํ™•์ธํ›„ Send ํด๋ฆญ

Body๋ถ€๋ถ„์— ๊น€๋นต๋นต์˜ ์ผ์ƒ์˜ ์ €์ž ๊น€๋นต๋นต์ด ์ œ๋Œ€๋กœ ์ถœ๋ ฅ๋˜์—ˆ๋‹ค!

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

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