[Spring Boot] 4. 간단한 GET API를 만든다(3/3)

0. 목표

 

[Mission-04] feat: add @PathVariable GET API by ssoyeong · Pull Request #8 · ssoyeong/spring-boot-study

미션 간단한 GET API를 만든다. 만든 API를 로컬 환경에서 테스트해본다. 스펙 GET localhost:8080/test/greeting/{name} 예시 # 요청 GET localhost:8080/test/greeting/ssoyeong # 응답 Hello, ssoyeong! 세부 내용 @PathVariable 어

github.com

아래 API를 개발하자

 

스펙

GET localhost:8080/test/greeting/{name}

 

예시

# 요청
GET localhost:8080/test/greeting/ssoyeong

# 응답
Hello, ssoyeong!

 

1. URL Parameter란?

1.1. 개념

.URI의 일부로, 일반적으로 path 뒤에 오며 특정 리소스의 구체적인 위치나 리소스에 대한 정보를 전달하는 데 사용됨

ex) https://example.com/users/123 에서 "123"은 "users" 리소스의 특정 사용자 ID를 나타내는 URL Parameter임

 

1.2. 특징

RESTful API 디자인에 자주 사용되며, 리소스의 고유한 식별자나 키로 사용됨

 

1.3. 사용 용도

주로 CRUD 작업에서 특정 리소스의 항목을 식별할 때 사용됨

 

1.4. 다루기 좋은 데이터

고유한 식별자나 키값 같은 단일 데이터를 다루기에 적합함

ex) 사용자 ID, 상품 코드, 게시글 번호 등

 

1.5. 주의사항

- URL Parameter 값은 고유해야 함. 그렇지 않으면 예상치 못한 리소스에 접근하게 됨

- 보안적인 문제로 민감한 정보(비밀번호, 토큰 등)를 전달하는 데 사용되어서는 안됨

- URL 길이에는 제한이 있으므로, 너무 많은 정보를 URL Parameter로 전달하면 문제가 발생할 수 있음

 

2. Spring에서 URL Parameter를 다루는 방법

'http://localhost:8080/test/greeting/ssoyeong'의 형태로 들어오는 URL은 @PathVariable 어노테이션을 사용한다.

@PathVariable는 URI의 일부로 전달된 값을 컨트롤러 메서드의 인자로 바인딩할 때 사용하는 어노테이션이다.

 

2.1. 기본 사용

@GetMapping("/users/{userId}")
public String getUser(@PathVariable String userId) {
    return "User ID: " + userId;
}

 

2.2. 다른 변수명으로 바인딩

@GetMapping("/users/{id}")
public String getUserById(@PathVariable("id") String userId) {
    return "User ID: " + userId;
}

 

2.3. 여러 URL Parameter 받기

@GetMapping("/users/{userId}/orders/{orderId}")
public String getOrderOfUser(@PathVariable String userId, @PathVariable String orderId) {
    return "User ID: " + userId + ", Order ID: " + orderId;
}

Map으로 받을 수도 있으나, 코드의 가독성을 떨어뜨릴 수 있으므로 일반적으로는 각 @Pathvariable의 값을 개별 변수에 명시적으로 바인딩하는 것이 권장된다.

 

2.4. 정규 표현식으로 제한

@GetMapping("/products/{id:[\\d]+}")
public String getProduct(@PathVariable Long id) {
    return "Product ID: " + id;
}

정규 표현식을 사용해 값을 제한할 수 있다. 위 예제는 숫자만 가능하도록 제한한다.

 

2.5. URL Parameter와 Query String을 함께 사용하는 경우

@GetMapping("/users/{userId}/orders")
public String getUserOrdersByStatus(@PathVariable String userId, @RequestParam String status) {
    return "User ID: " + userId + ", Orders with status: " + status;
}

'/users/{userId}/orders?status=shipped'의 형태로 들어오는 URL을 처리하는 예제이다.

 

3. 코드

package com.ssoyeong.studyapplication.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

    @GetMapping("/test/hello")
    public String getHello() {
        return "Hello world!";
    }

    @GetMapping("/test/greeting")
    public String getGreeting(@RequestParam String name) {
        return String.format("Hello, %s!", name);
    }

    @GetMapping("/test/greeting/{name}")
    public String getGreeting2(@PathVariable String name) {
        return String.format("Hello, %s!", name);
    }
}