Programming/Spring

스프링부트 API - GET Method 활용하기

긍정왕웹서퍼 2022. 4. 3. 00:00
728x90

개요

API와 GET Method를 이해하고 활용하는 다양한 방법을 알아보기

 

GET 어노테이션의 종류

  • @RequestMapping : value와 method로 정의하여 API를 개발하는 방식으로 요즘 추세는 사용하지 않는 편
  • @GetMapping : 별도의 파라미터 없이 GET API를 호출하는 경우 사용되는 방법
  • @PathVariable : GET형식의 요청에서 파라미터를 전달하기 위해 URL에 값을 담아 요청하는 방법 
  • @RequestParam : GET형식의 요청에서 쿼리 문자열을 전달하기 위해 사용되는 방법 
// 1. ReqeustMapping
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String requestTest() {
	return "request testing";
}

// 2. GetMapping(without Param)
@GetMapping(value = "/name")
public String getName(){
	return "mason";
}

// 3. PathVariable
@GetMapping(value="/variable1/{var}")
public String getVariable1(@PathVariable String var) {
	return var;
}

// 3-2. PathVariable
@GetMapping(value="variable2/{var}")
public String getVariable2(@PathVariable("variable") String var) {
	return var;
}

// 4. ReqeustParam '?'를 기준으로 우축에 {key}={value}형태로 전달되며 복수로 '&' 를 사용하는 경우 
// https://goodthinking.tistory.com/newpost/?name=goodthinking&title=스프링부트GET-API
@GetMapping(value="/request1")
public String getRequestParam1(
	@RequestParam String name,
    @RequestParam String title) {
	return name + title;
}

// 4-2. ReqeustParam 어떤 요청값이 들어올지 모를 경우 
@GetMapping(value="/request2")
public String getRequestParam2 (@RequestParam Map<String, String> param) {
	StringBuilder sb = new StringBuilder();
    param.entrySet().forEach(map -> {
    	sb.append(map.getKey() + ":" + map.getValue() + "\n");
    });
    return sb.toString();
}

// 4-3. DTO를 활용하는 경우
@GetMapping(value="/request3")
public String getRequestParam3(MemberDTO member) {
	return member.toString();
}
//DTO
public class MemberDTO{
	private String name;
    private String title;
....
}

 

 

자!

이렇게 예제 API를 프로젝트로 생성해 실행하게 되면 

웹으로 실행하는 API tester 를 통해 그 반환값을 확인할 수 있다.

대표적인 종류로 API postman

 

Postman API Platform | Sign Up for Free

Postman is an API platform for building and using APIs. Postman simplifies each step of the API lifecycle and streamlines collaboration so you can create better APIs—faster.

www.postman.com

혹은 Talend-API-Tester

 

Talend API Tester - Free Edition

Visually interact with REST, SOAP and HTTP APIs.

chrome.google.com

를 활용하여 그 결과값을 실시간으로 손쉽게 확인할 수 있어 아주아주 편리하다.