[Spring Boot] GET API 2 - 매개변수 받는 메서드 (@PathVariable)

박현아·2025년 2월 26일
0

Spring Boot

목록 보기
3/5

*<스프링 부트 핵심 가이드>에 나온 내용을 실습해보는 포스팅입니다.

🥕 GET API 실습 - 매개변수 받는 메서드 (@PathVariable)

@PathVariable이란?

✔️ @PathVariable은 URL 경로(Path)에서 값을 추출하여 컨트롤러 메서드의 매개변수로 전달할 때 사용하는 어노테이션이다.
예 : /users/10에서 10을 id로 받아 처리 가능.
✔️ RESTful API에서 리소스를 식별할 때 적합하며, 가독성이 뛰어난 URL을 만들 수 있다.

package com.springboot.api.controller;

import java.util.Map;

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

import com.springboot.api.dto.MemberDTO;

@RestController
@RequestMapping("/api/v1/get-api")
public class GetController {

	// @PathVariable 사용 - 매개변수를 받는 메서드 사용 시 
	@GetMapping("/variable1/{variable}")
	public String getVariable1(@PathVariable String variable) {
		return variable;
	}

	// @ 어노테이션의 변수와 메서드 매개 변수의 이름을 동일하게 맞추기 어려울 때 
	@GetMapping("/variable2/{variable}")
	public String getVaribale2(@PathVariable("variable") String var) {
		return var;
	}

}

동작 테스트


http://localhost:8080/api/v1/get-api/variable1/test
이렇게 요청하면 {variable} 부분에 입력한 test가 잘 나오는 것을 확인할 수 있다.


http://localhost:8080/api/v1/get-api/variable2/test2
이렇게 요청하면 test2도 잘 나온다.

0개의 댓글