분석설계고민

HttpStatus 잘 사용하는법

닥치고개돌 2024. 3. 21. 11:48
728x90

RestAPI 요청을 하면 HTTP status와 함게 응답을 내려준다.
이 글은 요청에 대한 값이 없을때 http status가 200인가,400인가 ,404인가에 대한 고민을 하다가 찾아본 결과를 정리하는 글이다.

Resources와 representation의 차이

먼저 RFC에서 404 Not Found에 대한 정의를 보자

 

[https://tools.ietf.org/html/rfc7231#section-6.5.4](https://tools.ietf.org/html/rfc7231#section-6.5.4)The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not    willing to disclose that one exists. A 404 status code does not    indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.   
A 404 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see  
 [Section 4.2.2 of [RFC7234]](https://datatracker.ietf.org/doc/html/rfc7234#section-4.2.2)).

 

요청한 리소스가 없을 때 가리킨다. 더 정확히는 요청한 리소스에 대한 현재 representation 을 찾을 수 없을 때 사용한다고 한다. 간단하게 설명하면 해당 링크가 존재하지 않는다는 뜻

여기서 resource와 representation을 구분해보자

GET 메서드의 정의는 다음과 같다.

 

The GET method requests transfer of a current selected representation
for the target resource.

 

즉, target resource에 대한 현재의 선택된 representation 하나를 반환한다.

위 정의에서 “target resource”란 https://example.org/greeting 라는 uri가 가리키는 리소스, 바로 HTTP 요청의 대상이다.


그럼 “현재의 선택된 representation”이란 무엇인가? 어떤 리소스의 특정 시점의 상태를 반영하고 있는 정보이다. 하나의 representation은 representation data와 representation metadata로 구성된다.

위의 리소스에서 hello라는 응답이 왔으면 “hello”가 representation data이고, “Content-Type: text/plain”과 “Content-Language: en”이 representation metadata이다.

 

쉽게말해 resource는 요청한 uri, representation은 리소스에 대한 리턴값이라고 생각하면된다. 즉 성공시 리턴값, 실패시 에러메시지 또한 representation이다.
-> 사실 깊게 들어가면 http메시지의 payload로 전달되는 모든 것도 하나의 representation이지만 여기선 httpstatus에 대한 주제를 다룸으로 리턴값으로만 한정. 자세한 내용은 (https://blog.npcode.com/2017/04/03/rest%EC%9D%98-representation%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80/)


 

더 자세히 정리하고 싶었지만 계속된 조사결과 해당 문제는 필수가 아닌 개발 규칙에 맞게 적용하면 되는것 같다.
실제로 많은 회사들이 자신들만의 규칙을 정해놓고 사용중이었다.

그래서 조사한 결과를 바탕으로 결로만 정리해보면

 

GET /users/{userId} : 조회한 userId가 없을경우 404
-> 위에 첨부된 404 내용을 보면 리소스가 존재하고, 그에대한 응답(에러메시지)도 존재함으로 404가 적합함

 

GET /usersff/{userId} : 해당 리소스가 없음으로 404

 

GET /users?name='test' : 검색한 name이 없을경우 200
-> /users란 리소스는 존재, representation도 빈값으로 존재

 

POST /users/login : 로그인 요청시 페이로드가 잘못된경우 ??
-> 가장 논란이 많은부분. 계정이 없는경우 400, 404, 200 등 다양한 의견이 있다.
내용을 들어보면 모두 그럴듯함. 400은 로그인은 이미 존재하는 계정이라는 전제하에 시도하는데 없는 계정을 요청했다면 요청자체가 잘못이라 400이다, 없는 계정요청이니 404다, 요청은 성공했고 로그인에 대한 예외상태를 상세히 나누면 해커들의 먹이가되기에 200으로 하고 로그인 실패만 나타낸다 등.
고민하고 회사에 맞게 잘 사용하면 될듯

 

 

나머지 부분은 논란의 여지가 크지않아 명세에 맞게 잘 사용하면 될듯!

728x90

'분석설계고민' 카테고리의 다른 글

msa란? msa 고도화  (0) 2024.02.04
php에서 java로 전환하기(작성중)  (1) 2024.01.29
트랜잭션에 대한 고민  (0) 2023.12.29