Post

다양한 방법으로 api 작성하기

다양한 방법으로 api 작성하기

다양한 방법으로 API 작성하기

@Controller & @RestController

@Controller

HTML 등 View를 반환할 때 사용



@RestController(@Controller + @ResponseBody)

데이터를 JSON / XML 형식으로 반환

응답 데이터를 자동으로 JSON 형식으로 변환하고 Content-Typeapplication/json으로 설정



@ResponseBody

자바 객체를 HTTP 응답 본문(Body)에 직접 매핑

  • @RequestBody : HTTP 요청 Body → Java 객체
  • @ResponseBody : Java 객체 → HTTP 응답 Body
1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/api")
public class ExampleController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, World!";
    }
}






요청 매핑과 데이터 처리

GET / DELETE 메서드: URL에 데이터 포함

GET과 DELETE 메서드는 URL 경로 또는 쿼리 파라미터를 통해 데이터를 전달받는다.


@PathVariable : URL 경로에서 데이터 추출

1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("/api")
public class MyController {

    // http://localhost:8080/api/hello/coco
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable String name) {
        return "Hello, " + name;
    }
}
1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("/api")
public class MyController {

    // http://localhost:8080/api/hello/coco
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String userName) {
        return "Hello, " + userName;
    }
}

@GetMapping에 정의한 변수명과 메서드 파라미터명이 다를 경우 위와 같이 명시적으로 매핑할 수 있다.



@RequestParam : 쿼리 파라미터로 데이터 추출

쿼리 파라미터는 URL 뒤에 ?key=value 형태로 전달된다.

여러 개의 파라미터는 &로 연결한다.

1
2
3
4
5
6
7
8
9
10
11
@RestController
@RequestMapping("/api")
public class MyController {

    // http://localhost:8080/api/hello?name=coco&age=5
    @GetMapping("/hello")
    public String hello(@RequestParam("name") String name,
                        @RequestParam("age") int age) {
        return "Hello, " + name + ", " + age;
    }
}




POST / PUT 메서드: HTTP Body에 데이터 포함

POST와 PUT 메서드는 데이터를 HTTP Body에 JSON 형식으로 전달


@RequestBody : JSON → Java 객체 변환

1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/api")
public class MyController {

    @PostMapping("/user")
    public MyDTO postUser(@RequestBody MyDTO myDTO) {
        return myDTO;
    }
}

DTO 객체를 반환할 경우 getter가 없으면
HttpMediaTypeNotAcceptableException이 발생할 수 있다.


@ModelAttribute : Form 데이터 바인딩

Form 데이터를 객체로 매핑할 때 사용

1
2
3
4
let form_data = new FormData();
form_data.append("comment", $("#comment").val());
form_data.append("nickname", nickname);
form_data.append("registryIdx", $("#RegistryId").html());
1
2
3
4
@PostMapping("/comment")
public Comment setComment(@ModelAttribute CommentDto commentDto) {
    return commentService.setComment(commentDto);
}

@ModelAttribute는 타입 변환 및 검증 과정이 포함된다.






DTO와 ResponseEntity

DTO (Data Transfer Object)

계층 간 데이터 전달을 목적으로 사용하는 객체

비즈니스 로직 없이 순수 데이터만 포함한다.

1
2
3
4
5
6
7
public class UserDto {

    private String username;
    private String email;

    // getters, setters
}



ResponseEntity

HTTP 상태 코드와 응답 데이터를 함께 제어할 때 사용

1
2
3
4
@PostMapping("/user")
public ResponseEntity<UserDto> createUser(@RequestBody UserDto userDto) {
    return ResponseEntity.status(HttpStatus.CREATED).body(userDto);
}






URI Mapping

  • value : 요청 URL
  • method : HTTP 메서드
1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/api")
public class MyController {

    @RequestMapping(value = "/study", method = RequestMethod.POST)
    public String createStudy() {
        return "Study Created";
    }
}


간편한 매핑 방식

Spring 4.3 이후부터는 전용 annotation을 사용할 수 있다.

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/study")
public class StudyController {

    @GetMapping("/ch3")
    public String studyNoCh3() {
        return "chapter 3";
    }
}

/study/ch3 요청 시 해당 메서드가 실행






HTTP 메서드별 데이터 처리 예시

데이터 전달 방식

POST / PUT

  • HTTP Body
  • JSON 형식
  • 반드시 JSON.stringify() 사용
1
2
3
4
5
6
7
8
9
10
11
let data = { username: 'example', contents: 'message' };

$.ajax({
    type: "PUT",
    url: `/api/${id}`,
    contentType: "application/json",
    data: JSON.stringify(data),
    success: function (response) {
        console.log(response);
    }
});



GET / DELETE

  • URL에 데이터 포함
1
2
3
4
5
6
7
$.ajax({
    type: "DELETE",
    url: `/api/${id}`,
    success: function (response) {
        console.log(response);
    }
});



POST

1
2
3
4
@PostMapping("/create")
public UserDto createUser(@RequestBody UserDto userDto) {
    return userDto;
}



GET

1
2
3
4
@GetMapping("/user/{id}")
public String getUser(@PathVariable Long id) {
    return "User ID: " + id;
}



PUT

1
2
3
4
@PutMapping("/update")
public ResponseEntity<UserDto> updateUser(@RequestBody UserDto userDto) {
    return ResponseEntity.ok(userDto);
}



DELETE

1
2
3
4
@DeleteMapping("/user/{id}")
public String deleteUser(@PathVariable Long id) {
    return "Deleted User ID: " + id;
}






REFERENCE

This post is licensed under CC BY 4.0 by the author.