Dev/Spring Boot

Swagger ๋ž€? ๋ฌด์—‡์ธ๊ณ ?

OK-๊ฐ€์ž 2022. 3. 2. 17:42

๐Ÿค” Swagger ๋ž€?

Swagger๋ž€ ๊ฐœ๋ฐœํ•œ Rest API๋ฅผ ํŽธ๋ฆฌํ•˜๊ฒŒ ๋ฌธ์„œํ™” ํ•ด์ฃผ๊ณ , ์ด๋ฅผ ํ†ตํ•ด์„œ ๊ด€๋ฆฌ ๋ฐ ์ œ 3์˜ ์‚ฌ์šฉ์ž๊ฐ€ ํŽธ๋ฆฌํ•˜๊ฒŒ API๋ฅผ ํ˜ธ์ถœํ•ด๋ณด๊ณ  ํ…Œ์ŠคํŠธ ํ•  ์ˆ˜ ์žˆ๋Š” ํ”„๋กœ์ ํŠธ ์ด๋‹ค.

Spring Boot์—์„œ๋Š” ๊ฐ„๋‹จํ•˜๊ฒŒ springfox-boot-starter ๋ฅผ gradle dependencies์— ์ถ”๊ฐ€ ํ•จ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋‹ค๋งŒ, ์ฃผ์˜ํ•  ์ ์€ ์šด์˜ํ™˜๊ฒฝ๊ณผ ๊ฐ™์€ ์™ธ๋ถ€์— ๋…ธ์ถœ๋˜๋ฉด ์•ˆ๋˜๋Š” ๊ณณ์—์„œ ์‚ฌ์šฉํ•  ๋• ์ฃผ์˜ ํ•ด์•ผ ํ•œ๋‹ค.

์‚ฌ์šฉํ•ด๋ณด์ž.

โœ… ๋””ํŽœ๋˜์‹œ ์„ค์ •

// https://mvnrepository.com/artifact/io.springfox/springfox-boot-starter
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: '3.0.0'

โœ… ์ปจํŠธ๋กค๋Ÿฌ ํ•˜๋‚˜ ๋งŒ๋“ค๊ณ 

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/hello")
    public String hello(){
        return "hello swagger";
    }
}

โœ… ์ด์ œ TalendAPI๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ Testํ•˜์ง€ ์•Š๊ณ  localhost:8080/swagger-ui/๋กœ ๋“ค์–ด๊ฐ€๋ฉด๋จ

  • ์ด๋ ‡๊ฒŒ ํ•˜๋ฉด ํ˜„์žฌ ๋‚ด๊ฐ€ ๋งŒ๋“  API๋ฅผ ๋ณผ์ˆ˜ ์žˆ๊ณ  Test๋„ ์‰ฝ๊ฒŒ ํ•ด๋ณผ์ˆ˜ ์žˆ๋‹ค.

โœ… @Api Controller ์„ค๋ช… ๋„ฃ๊ธฐ

@Api(tags = "API์ •๋ณด๋ฅผ ์ œ๊ณตํ•˜๋Š” Controller")
@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/hello")
    public String hello(){
        return "hello, Swagger";
    }
}

๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡

โœ… @Get ๋ฐฉ์‹์˜ PathParam ์‚ฌ์šฉ๊ณผ RequestRaram ์‚ฌ์šฉ

    @GetMapping("/plus/{x}")
    public int plus(@PathVariable int x, @RequestParam int y){
        return x+y;
    }

)

์ •๋ง ๊ฐ„ํŽธํ•˜๋‹ค.
โœ… ์ถ”๊ฐ€๋กœ @ApiParam์„ ์‚ฌ์šฉํ•˜๋ฉด

            @ApiParam(value = "X๊ฐ’")
            @PathVariable int x,

            @ApiParam(value = "y๊ฐ’")
            @RequestParam int y){


โœ… ๋ชฐ๋ก  ApiImplicitParms๋ฅผ ์ด์šฉ์•ผ์—ฌ Param๋“ค์˜ ์ •์˜๋ฅผ ํ•œ๋ฒˆ์— ํ• ์ˆ˜๋„ ์žˆ๋‹ค.

    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "์‚ฌ์šฉ์ž ์ด๋ฆ„", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "age", value = "์‚ฌ์šฉ์ž ๋‚˜์ด", required = true, dataType = "int", paramType = "query")
    })

โœ… DTO์—๋„ ๋ช…์‹œ์ ์œผ๋กœ ํ‘œํ˜„ํ• ์ˆ˜ ์žˆ๋‹ค.

@AllArgsConstructor
@NoArgsConstructor
@Data
public class UserResponse {

    @ApiModelProperty(value = "์‚ฌ์šฉ์ž ์ด๋ฆ„", example = "steve")
    private String name;


    @ApiModelProperty(value = "์‚ฌ์šฉ์ž ๋‚˜์ด", example = "10")
    private int age;
}

โœ… ๋งˆ์ง€๋ง‰์œผ๋กœ error ๋ถ€๋ถ„๋„ ๋”ฐ๋กœ ์ •ํ• ์ˆ˜ ์žˆ๋‹ค.

    @PostMapping("/user")
    @ApiResponse(code = 404, message = "not found")
    public UserResponse post(@RequestBody UserRequest userRequest){
        return new UserResponse(userRequest.getName(), userRequest.getAge());
    }