개발공부/Spring Boot

[Spring Boot] GET API

환타몬 2022. 2. 8. 16:23

위의 그림의 GetApIController 클래스를 이용하여 GET API를 사용해볼 것이다.

package com.example.hello.controller;

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

@RestController
@RequestMapping("/api/get")
public class GetApIController {

    @GetMapping(path = "/hello") // http://localhost:9090/api/get/hello
    public String hello(){
        return "get Hello";
    }

    @RequestMapping(path = "/hi", method = RequestMethod.GET) // get http://localhost:9090/api/get/hi
    public String hi(){
        return "hi";
    }
}

- @RestController 를 붙임으로써 해당 클래스는 REST를 처리하는 Class임을 나타낸다.

- @RequsetMapping은 URI를 지정해주는 어노테이션

- 예전에는 RequestMapping을 이용해서 get, put ,delete, update 등을 정해서 주었지만 이젠 GetMapping과 같은 Annotation을 통해서 가능.

 

 

- 주소가 매번 변

//http://localhost:9090/api/get/path-variable/{name}
    // 주소에는 대문자를 쓰지 않기 때문에 하이픈(-)을 이용해서 가독성 높이기기
    @GetMapping("/path-variable/{name}")
    public String pathVariable(@PathVariable String name){

        System.out.println("PathVarialbe: "+name);

        return name;
    }
}

- 똑같이 GetMapping을 사용하지만 변하는 부분을 {name}으로 준다.

- pathVariable에 매개변수로 String 타입의 name을 변수로 주는데, 파라미터 안에 @PathVariable 어노테이션을 사용한다.

- 변수의 name을 맞춰주어야 한다. 

 

=== 출력 결과 ===

 

- 매개 변수로 name을 여러 개를 받을 경우

    //http://localhost:9090/api/get/path-variable/{name}
    // 주소에는 대문자를 쓰지 않기 때문에 하이픈(-)을 이용해서 가독성 높이기기
    @GetMapping("/path-variable/{name}")
    public String pathVariable(@PathVariable(name = "name") String pathName){

        System.out.println("PathVarialbe: "+pathName);

        return pathName;
    }
}

 

 

 

- Queryparam 쓰는 법

 // http://localhost:9090/api/get/query-param?user=steve&email=steve@gamil.com&age=30
    @GetMapping(path = "query-param")
    public String QueryParam(@RequestParam Map<String, String> queryParam){
        StringBuilder sb = new StringBuilder();

        queryParam.entrySet().forEach(entry ->{
            System.out.print(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");

            sb.append(entry.getKey() + "="+entry.getValue()+"\n");

        });
        return sb.toString();
    }

=== 출력 화면 ===

 

- queryParam02 

위와 같이 Map형태로 사용하게 된다면 매개변수로 무엇이 들어갔는지 알 수 없다.

그래서 명시적으로 매개변수를 선언해주는 방법으로 진행하려고 한다.

 

@GetMapping("query-param02")
    public String queryParam02(
            @RequestParam String name,
            @RequestParam String email,
            @RequestParam int age
    ){
        System.out.println(name);
        System.out.println(email);
        System.out.println(age);

        return name+" "+email+" "+age;

    }

 

-dto를 만들어서 객체로 불러오기

 

- queryParam03

이전에 매개변수 어노테이션으로 @RequestParam을 사용했는데, 이것 보다는 객체를 생성해서 바로 queryParameter가 바로 매핑이 될 수 있는 형태를 선호한다.

 

UesrRequest.java

package com.example.hello.dto;

public class UserRequest {

    private String name;
    private String email;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "UserRequest{" +
                "name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

 

- 객체로 받기

 @GetMapping("query-param03")
    public String queryParam03(UserRequest userRequest){
        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());

        return userRequest.toString();
    }