[스프링부트] Spring Boot / Rest Client 설치

Harry park·2021년 12월 23일
0

SpringBoot

목록 보기
2/11
post-thumbnail

스프링 부트(Spring Boot)

스프링 부트

: 단순하게 실행되며, 프로덕션 제품 수준의 스프링 기반 어플리케이션을 쉽게 만들 수 있도록 해주는 프레임워크

  • spring 구성이 거의 필요하지 않다.

  • Java -jar로 실행하는 Java Application을 만들 수 있다.

  • 기본값 설정이 있지만 설정을 바꿀 수 있다.

  • 대규모 프로젝트에 공통적인 비 기능을 제공한다.(보안, 모니터링)

  • XML구성 요구 사항이 전혀 없다.


REST Client 설치

  • 크롬 웹 스토어에 접속하여, Talend API Tester 검색 후 설치
    Talend API Tester

HELLO Spring Boot 출력

Spring Boot 생성

  • Java
  • Gradle
  • JDK 11

server port를 변경하는 방법

  • src\main\resources\application.properties
    server.port="원하는포트" 를 입력하면 된다.

프로젝트 생성

Test를 위해 com.example.tldspringboot.controller 패키지를 생성하고 하위에 ApiController클래스를 생성한다.

  • Get API

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

    @GetMapping(path = "/hello") // http://localhost:8080/api/get/hello
    public String getHello() {
        return "get Hello Spring Boot!";
    }

    // 구버전
    @RequestMapping(path = "/hello2", method = RequestMethod.GET) // get, post, put, delete
    public String oldRequestMapping() {
        return "get Hello Spring Boot!";
    }

    @GetMapping("/path-variable/{name}") // http://localhost:8080/api/get/path-variable/{name}
    public String pathVariable(@PathVariable(name = "name") String pathName) {

        System.out.println("Path Variable : " + pathName);
        return pathName;
    }

    // http://localhost:8080/api/get/query-param?user=devharry&email=harry@email.com&age=30
    @GetMapping(path ="/query-param")
    public String queryParam(@RequestParam Map<String, String> queryParam) {
        StringBuffer sb = new StringBuffer();
        queryParam.entrySet().forEach(entry -> {
            sb.append(entry.getKey() + " : " + entry.getValue() + "\n");
        });
        return sb.toString();
    }

    // 변수가 많아지게 되면 모두 추가되어야 한다는 단점이 있다.
    @GetMapping(path ="/query-param02")
    public String queryParam02(@RequestParam String name,
                               @RequestParam String email,
                               @RequestParam int age) {

        return "name : " + name + ", email : " + email + " , age : " + age ;
    }

    @GetMapping(path ="/query-param03")
    public String queryParam03(UserRequest userRequest) {

        return userRequest.toString();
    }
  • POST API
    : 주로 데이터를 주고 받을 때는 XML, JSON을 사용한다.

JSON의 기본 구조
{
"key" : "value"
}
JSON value로 가능한 것들
String : value
number : value
boolean : value { }
object : value
array : value 대괄호로 묶인다.

snake case

: 단어의 구분마다 '_'를 사용

camel case

: 단어의 구분마다 UpperCase

예시

{ "phone_number" : "010-1111-2222",
  "age"	: 10,
  "isAgree" : false,
  "account" : {
  		"email" : "address@domain.com",
        	"password" : "password1234"
  		},
}
//  user조회
{
	"user_list" : [
    	{
        	"account" : "abcd",
        	"password" : "1234"
        },
        {
        	"account" : "abcdef",
        	"password" : "1234aa"
        }
    ]
}
package com.example.tldspringboot.controller;

import com.example.tldspringboot.dto.PostRequestDto;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

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

    @PostMapping("/post")
    public void post(@RequestBody Map<String, Object> requestData) {
        System.out.println(new Object(){}.getClass().getEnclosingMethod().getName());
        requestData.forEach((key, value) -> {
            System.out.println("key : " + key + " -> value : " + value);
        });
    }

    @PostMapping("/dto-post")
    public void dtoPost(@RequestBody PostRequestDto requestData) {
        System.out.println(new Object(){}.getClass().getEnclosingMethod().getName());
        System.out.println(requestData);
    }

}
  • PUT API
    :주로 데이터를 갱신하거나 추가할 때 이용한다.
package com.example.tldspringboot.controller;

import com.example.tldspringboot.dto.PutRequestDto;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class PutApiController {

    @PutMapping(path = "/put")
    public PutRequestDto put(@RequestBody PutRequestDto request){
        System.out.println(request);
        // RestController는 ObjectMapper에서 그대로 리턴해줌.
        return request;
    }

    @PutMapping(path = "/put/{userId}")
    public PutRequestDto putPathVariable(@RequestBody PutRequestDto request, @PathVariable("userId") Long userId){
        System.out.println(request);
        System.out.println("userId : " + userId);
        // RestController는 ObjectMapper에서 그대로 리턴해줌.
        return request;
    }
}
  • DELETE API
    : 리소스를 삭제한다.
    : 삭제되는 순간 데이터가 지워지는 것으로 안정성이 없다.
package com.example.tldspringboot.controller;

import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class DeleteApiController {

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

Response 내려주기

Return Text
Return JSON
Return JSON & Status ( PUT은 200,201을 넘겨줌)


@RestController
@RequestMapping("/api")
public class ApiResponseController {

    @GetMapping("/text")
     public String textReturn(@RequestParam String account) {
        return account;
     }

     @PostMapping("/json")
    public UserRequest jsonReturn(@RequestBody UserRequest user){
        return user;
    }

    @PutMapping("/put-res")
    public ResponseEntity<UserRequest> putResponse(@RequestBody UserRequest user) {
        return ResponseEntity.status(HttpStatus.CREATED).body(user);
    }
profile
Jr. Backend Engineer

0개의 댓글