본문 바로가기

Web/Spring

[Spring] Query Parameter와 Path Variable

HTTP GET 메소드로 데이터를 교환할 때 어떤 방식으로 사용해야 할지 알아본다.

Query Parameter

/user?occupation=programmer

Query Parameter는 resource의 필터링이나 정렬이 필요할 때 사용한다.

위의 경우 user들 중 직업이 programmer인 user만을 가져온다.

1
2
3
4
5
6
@GetMapping("/user")
public String getByQueryParameter(@RequestParam("occupation"String occupation){
   System.out.println(occupation);
   // output : programmer
}
 
cs

Spring에서는 @RequestParam을 통해 Query Parameter를 가져올 수 있다.

Path Variable

/user/123

Path Variable은 resource의 식별이 필요할 때 사용한다.

위의 경우 user의 id가 123인 유저만을 가져온다.

1
2
3
4
5
@GetMapping("/user/{id}")
public String getByPathVariable(@PathVariable("id"int id){
    System.out.println(id);
    // output : 123
}
cs

Spring에서 @PathVariable을 통해 Path Variable을 가져올 수 있다.

HTTP Method 활용

위에서는 GET만을 이야기 했지만, 기본적인 CRUD의 경우 HTTP Method를 활용하면 추가적인 QueryParameter나 (user?action=create) Path Variable (user/create)를 추가할 필요 없이 URL을 설계할 수 있다.

/user [POST] // 새로운 user 생성
/user [GET] // 모든 유저 정보 list 받아오기
/user/123 [GET] // id가 123인 user 정보 받아오기
/user/123 [PUT] // id가 123인 user 정보 수정하기

위와 같이 더 깔끔하고 간단하게 URL을 설계하는 것이 잠재적인 커뮤니케이션 비용을 줄이는 데에 좋을 것이다.

 


 

 

When Should You Use Path Variable and Query Parameter?

In this article, I’d like to show you what is a Path Variable and Query Parameter. And how you think and use those as best practice.

medium.com