상세 컨텐츠

본문 제목

ch4. API만들기 _ REST Client 설치, controller생성, get api 생성

패캠스프링/part3._스프링입문(part3)

by hippo0207 2022. 7. 29. 00:18

본문

  • 주소에 대문자 안씀 a-b로 함

1. REST Client 설치

https://chrome.google.com/webstore/detail/talend-api-tester-free-ed/aejoelaoggembcahagimdiliamlcdmfm?utm_source=chrome-ntp-icon 

 

Talend API Tester - Free Edition

Visually interact with REST, SOAP and HTTP APIs.

chrome.google.com

  • hello 프로젝트 새로 생성함. (dependency : Spring web만 넣음)
  • 톰캣등 설정원할때 : resources > applicatoin.properties 
server.port = 9090

2. controller 만들기

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.RestController;

@RestController // 해당 class : restApi 처리하는 controller로 등록됨
@RequestMapping("/api") // URI을 지정해주는 annotation
public class ApiController {


    @GetMapping("/hello") // http://localhost:8080/api/hello 로 매핑
    public String hello(){
        return "hello spring boot";
    }

}

ch.4.3 GET API (1)

  • RequestMapping 
  • RequestMapping + RequestMethod.GET == GetMapping
@RestController
@RequestMapping("/api/get")
public class GetApiController {



    //@RequestMapping("/hi") // get, post, put, delete 다 동작해버림
    @RequestMapping(path= "/hi", method= RequestMethod.GET) // get만 동작함 http://localhost:8080/api/get/hi
    public String hi(){
       return "hi";
    }

    //RequestMapping + RequestMethod.GET == GetMapping  <<<  <<<  <<<
    @GetMapping(path = "/hello") // http://localhost:8080/api/get/hello
    public String hello(){
        return "get Hello";
    }
  • PathVariable(name= "~~") : 바뀌는 변수를 주소에 담을때
  // http://localhost://8080/api/get/path-variable/{name}
    @GetMapping("/path-variable/{name}")
    //public String pathVariable(@PathVariable String name){ // {}안의 이름과 같아야 함. 이름다르게 되야할경우?
    public String pathVariable(@PathVariable(name = "name") String pathName, String name){ // pathName에 name값이 들어가게 됨 
        System.out.println("PathVariable : " + pathName);
        return pathName;
    }
    
    
  >>> http://localhost:8080/api/get/path-variable/java >>> java return함
  • queryParameter : @RequestParam 검색할때 검색인자 등등 ?ㄱㄱ&ㄴㄴ&ㄷㄷ&ㄹㄹ
  • queryParam 받기 3가지 방법
  • 1번째 Map으로 받기
//http://localhost:8080/api/get/query-param?user=steve&email=steve@gmail.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.println(entry.getKey());
            System.out.println(entry.getValue());
            System.out.println("\n");

            sb.append(entry.getKey() + " = " + entry.getValue()+ "\n") ;
        });
        return sb.toString();
    }
  • 미리 지정하고 받기
// 명확하게 사용할 queryParam key가 정해져있는 경우엔?
    @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 ;
    }
  • 3. dto만들어두고 받기  << @RequestParam 안붙임
// queryParam 받기 3번째 : dto만들기 (제일 많이씀)
    // 알수없는 값(dto에 없는)이 들어올경우는 >> 그값은 매칭안됨
    @GetMapping("query-param03")  // @RequestParam 붙이지 않음
    public String queryParam03(UserRequest userRequest){
        System.out.println(userRequest.getName());
        System.out.println(userRequest.getEmail());
        System.out.println(userRequest.getAge());
        return userRequest.toString() ;
    }
  • dto
package com.example.hello.dto;

public class UserRequest {
    private String name;
    private String email;
    private int age;

    public String getName() {
        return name;
    }
    ~~~~

 

4.4 Post API

  • json 규칙 : snake case(abc_def) > camel (abcDef)

1. post 

  • dto 먼저만들기
package com.example.hello.dto;

public class PostRequestDto {

    private String account;
    private String email;
    private String address;
    private String password;

    public String getAccount() {
        return account;
    }

 

  • @PostMapping  @RequestBody
@RestController
@RequestMapping("/api")
public class PostApiController {

    @PostMapping("/post")
 	//public void post(@RequestBody Map<String, Object> requestData){ 
    //    requestData.forEach((key, value) -> {
    //       System.out.println("key : " + key);
    //       System.out.println("value : " + value);
    //    });
    //} >> 이렇게하면 뭐가들어오는지 모름 dto로 하기 >>
    
     @PostMapping("/post")
    public void post(@RequestBody PostRequestDto requestData){
        System.out.println(requestData);
    }
}

>> 요즘 application/json default : utf-8 (예전엔 json:charset-utf-8 << 지정해야했음)

 

  • request 에서는 snake형식으로 들어오고, dto 에선 camel로 되어있으면?   
    • Object.mapper 라이브러리 사용할필요 있음
    • JsonProperty로 미리 지정해주기
    • @JsonProperty
@JsonProperty("phone_number")
private String phoneNumber;

@JsonProperty("OTP")
    private String OTP;

 

5. PUT API

  • Dto & object용으로 carDto도 생성
public class PutRequestDto {

    private String name;
    private int age;
    private List<CarDto> carList;

    public String getName() {
        return name;
    }

======================
public class CarDto {
    private String name;
    
    @JsonProperty("car_number")
    private String carNumber;

    public String getName() {
        return name;
    }
  • @JsonProperty 말고 다른 방법 (<<JsonProperty 는 한가지 property용 )
  • 클래스 전체적으로 같은룰 적용시키기 : @JsonNaming  >> carDto는 따로 해줘야함
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class PutRequestDto {

  • response 내려주기
    • RestController >> object리턴시키면 스프링부트가 이걸 objectMapper통해서 json으로 바꿔줌
    • @PutMapping @RequestBody @PathVariable
@RestController
@RequestMapping("/api")
public class PutApiController {

    @PutMapping("/put/{userId}")
    public PutRequestDto put(@RequestBody PutRequestDto requestDto, @PathVariable(name="userId") Long id){
        System.out.println(id);
        return requestDto;
    }
}

>> 굳이 문자열로 바꾸고 지랄발광안해도 됨

 

6. Delete API

  • @DeleteMapping @PathVarible @RequestParam
@RestController
@RequestMapping("/api")
public class DeleteApiController {

    @DeleteMapping("/delete/{userId}")
    public void Delete(@PathVariable String userId, @RequestParam String account){
        System.out.println("userId"+userId);
        System.out.println("account" + account);
    }

 

@RequestParam vs @PathVariable

@PathVariable은 어떤 요청이든 간에 딱 하나만 쓸 수 있습니다.

4. 정리/요약
1) @RequestParam 과 @PathVariable은 둘 다 데이터를 받아오는 데에 사용한다!

2) @PathVariable은 값을 하나만 받아올 수 있으므로, 쿼리스트링 등을 이용한
여러 개 데이터를 받아올 때는 @RequestParam을 쓴다!

3) @RequestParam은 uri를 통해 전달된 값이 아니더라도, ajax 요청을 통해 body에 담아온 데이터를 
여러 타입으로 받을 수 있다.

관련글 더보기

댓글 영역