티스토리 뷰

반응형

이번 회사로 이직 후 서버쪽 개발 업무 중 REST API 개발이 나의 main job이 되었다.

 

회사에서 생산하는 기기 및 App에게 효율적으로 정보를 제공해 줄 수 있는 서버쪽 프로그래밍인 셈이다.

회사에서 생산하는 기기역시 안에 내장된 OS는 안드로이드로 되어있기 때문에 가능한 일이다.

처음 RESTFul 에 대해서 대략적이게 알고 있었지만, 실무에서는 사용하지 않았기 때문에 달랐다.

또, mean stack이나 이런 스터디로 맛뵈기 했었다고 대례 이렇겠지 짐작했었지만 역시 실무와는 달랏다.

 

따라서 그에 따른 내용을 한번 정리해보려고 한다.

 

1. REST API란 무엇인가.

 

REST는 ROA를 따르는 웹 서비스 디자인 표준이다.

ROA : Resource Oriented Architecture

출처 : http://www.iamcorean.net/22

 

REST 는 네트워크 애플리케이션을 설계하는 아키텍처 스타일이다. 

기계와 연결하는 등의 CORBBA, PRC 또는 SOAP같은 복잡한 메커니즘을 사용하는 것보다, 간단한 HTTP 기반 (web service)으로 기계 사이의 통화를 하는데 사용된다.

 

What is REST?  

http://searchsoa.techtarget.com/definition/REST

http://rest.elkstein.org/

 

 

2. RESTful API Http Method 종류

 

RESTful API 설계시 URI 설계는 Resource에 접근하는것을 용이하게 나타내는 방식으로 주로 사용한다.

우선 RESTful API 설계시 HTTP method 구분부터 먼저 설명하도록 하겠다.

Resource에 대한 조회, 갱신, 입력, 삭제 들에 따라 각각 다른 HTTP method를 이용하여 작성한다.

 

아래 표를 인용해서 설명하겠다.

 

 

HTTP VerbCRUDEntire Collection (e.g. /customers)Specific Item (e.g. /customers/{id})

POST Create 201 (Created), 'Location' header with link to /customers/{id} containing new ID. 404 (Not Found), 409 (Conflict) if resource already exists..
GET Read 200 (OK), list of customers. Use pagination, sorting and filtering to navigate big lists. 200 (OK), single customer. 404 (Not Found), if ID not found or invalid.
PUT Update/Replace 404 (Not Found), unless you want to update/replace every resource in the entire collection. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
PATCH Update/Modify 404 (Not Found), unless you want to modify the collection itself. 200 (OK) or 204 (No Content). 404 (Not Found), if ID not found or invalid.
DELETE Delete 404 (Not Found), unless you want to delete the whole collection—not often desirable. 200 (OK). 404 (Not Found), if ID not found or invalid.

출처 : http://www.restapitutorial.com/lessons/httpmethods.html

 

서버에 있는 Database (Resource) 에 대한 요청을 보낼때 위와 같은 HTTP Method 를 이용하여 요청 및 처리를 하게 된다.

기존에 웹 개발을 해왔던 사람이라면 GET, POST를 이용하여 요청을 처리하였다. (이전 웹 에이전시 근무시 그렇게만 이용하였음.)

 

데이터 생성에 대한 작업을 할때는 post를 이용하여 작성하고, 요청이 정상적으로 수행되면 status 는 201번 그리고 생성된 자원을 접근할 수 있는 Location 값이 Header에 담겨져서 넘어온다.

 

데이터 조회에 대한 작업 요청시 GET을 이용하고 정상적으로 요청이 수행되면 status는 200번으로 응답한다.

 

데이터 갱신에 대한 작업 요청시 PUT을 이용하며, 정상적으로 요청이 수행되면 status는 200번으로 응답한다.

(PATCH와 PUT과 비슷하지만 조금 다른 의미를 띄고 있다.)

나는 전체적인 갱신과 부분적인 갱신에 따라 구분하여 사용하였다.

 

데이터 삭제에 대한 작업 요청시 DELETE를 이용하며, 정상적으로 요청이 수행되면 status는 200번으로 응답한다.

 

3. RESTful API design

 

API design 설계시 다음과 같은 사항을 고려해야 된다.

 

 - 웹 표준으로 사용되어야 한다.

 - 웹 브라우저 주소창의 URI를 통해 개발자 및 사용자가 친숙해야 한다.

 - 단순하고, 직관적이고 일관성있어야 한다.

 - 대부분의 Enchant UI에 충분한 유연성을 제공해야 한다. 

 - 다른도구 들과 균형있게 유지보수가 될 수 있도록 효과적이어야 한다.

 

위의 맥락으로 URL을 설계하면, 우리가 API 호출 링크를 보고 무슨 작업을 요청하는지를 알 수 있어야 한다.

예제 URL은 아래와 같다.

  • GET /tickets - Retrieves a list of tickets
  • GET /tickets/12 - Retrieves a specific ticket
  • POST /tickets - Creates a new ticket
  • PUT /tickets/12 - Updates ticket #12
  • PATCH /tickets/12 - Partially updates ticket #12
  • DELETE /tickets/12 - Deletes ticket #12

Ticket에 대한 CRUD를 설계한 예로,

GET /tickets 는 Ticket의 목록을 조회하겠다는 의미이다.

GET /tickets/12 는 Tickets 중 12번에 해당되는 애에게 접근하고 싶다는 의미이다.

POST /tickets 는 tickets 에 새로운 tickets을 생성하겠다는 의미이다.

PUT /tickets/12 는 12번의 ticket에 갱신을 하겠다는 의미이다.

DELETE /tickets/12 는 12번 ticket을 삭제하겠다는 의미이다.

 

Ticket과 다른 것의 관계에 대한 URL 설계는 아래와 같다.

 

  • GET /tickets/12/messages - Retrieves list of messages for ticket #12
  • GET /tickets/12/messages/5 - Retrieves message #5 for ticket #12
  • POST /tickets/12/messages - Creates a new message in ticket #12
  • PUT /tickets/12/messages/5 - Updates message #5 for ticket #12
  • PATCH /tickets/12/messages/5 - Partially updates message #5 for ticket #12
  • DELETE /tickets/12/messages/5 - Deletes message #5 for ticket #12

ticket과 message가 서로 관계가 있을때 접근 방법에 대해서 설명한 내용이다.

위에서 이야기 했던 내용과 비슷하므로 이해가 될 것이라 생각된다.

 

따라서 RESTful API의 설계는 개발자 및 사용자가 url을 보고 이해할 수 있도록 해주는 architecture 인 셈이다.

 

그 밖의 주의해야 될 점으로는 

RESTful API 사용에 있어서 SSL은 필수다.

그리고 RESTful API 버전관리는 처음 시작하는 URL 링크 앞에 /v1, /v2 등으로 구분하여 적용한다.

 

출처 : http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#restful

 

 

4. RESTful API Error Code 설계

 

  • 200 OK - Response to a successful GET, PUT, PATCH or DELETE. Can also be used for a POST that doesn't result in a creation.
  • 201 Created - Response to a POST that results in a creation. Should be combined with a Location header pointing to the location of the new resource
  • 204 No Content - Response to a successful request that won't be returning a body (like a DELETE request)
  • 304 Not Modified - Used when HTTP caching headers are in play
  • 400 Bad Request - The request is malformed, such as if the body does not parse
  • 401 Unauthorized - When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser
  • 403 Forbidden - When authentication succeeded but authenticated user doesn't have access to the resource
  • 404 Not Found - When a non-existent resource is requested
  • 405 Method Not Allowed - When an HTTP method is being requested that isn't allowed for the authenticated user
  • 410 Gone - Indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
  • 415 Unsupported Media Type - If incorrect content type was provided as part of the request
  • 422 Unprocessable Entity - Used for validation errors
  • 429 Too Many Requests - When a request is rejected due to rate limiting

 

위와 같이 사용된다고 나열되어있지만,

실제로 어느걸 사용할지는 각 개발팀의 몫인 것 같다.

많은 에러 코드들을 가지고 있으면 그에 따른 관리도 힘들고 개발도 힘들기 때문에 몇가지로 추려서 사용한다.

 

REST API 구현시 useful tool

POST Man : https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop

 - 크롬 플러그인으로서 사용하기 쉽고 편하다.

 

기타 스프링 boot를 이용하여 RESTful API를 개발하기 때문에,

junit test를 이용하여 mock mvc 를 이용해서 확인 할 수도 있고,

RestTemplate를 이용하여 검증할 수도 있다.

 

----------------------- 2016.10.04 추가 -----------------------------------

RestTemplate Example

http://www.javased.com/?api=org.springframework.http.HttpEntity

Java Code Examples of org.springframework.http.HttpEntity

www.javased.com

 

public void changePassword(String token,String oldPassword,String newPassword){
  HttpHeaders headers=new HttpHeaders();
  headers.add(AUTHORIZATION_HEADER_KEY,token);
  HttpEntity info=new HttpEntity(headers);
  ResponseEntity<String> response=restTemplate.exchange(authorizationUrl + "/userinfo",HttpMethod.GET,info,String.class);
  Map<String,Object> responseMap=JsonUtil.convertJsonToMap(response.getBody());
  String userId=(String)responseMap.get("user_id");
  Map<String,Object> body=new HashMap<String,Object>();
  body.put("schemas",new String[]{"urn:scim:schemas:core:1.0"});
  body.put("password",newPassword);
  body.put("oldPassword",oldPassword);
  HttpEntity<Map> httpEntity=new HttpEntity<Map>(body,headers);
  restTemplate.put(authorizationUrl + "/User/{id}/password",httpEntity,userId);
}
 

 

여기서 자세히 봐야될 부분이 body 부분을 어떻게 넘겨주는지 부분이다.

 

이부분 때문에 -_-; 많이 헤맷다.

반응형

'Study > RESTful' 카테고리의 다른 글

RESTful API HTTP status 정리  (0) 2019.04.10
RESTful api HTTP header method  (0) 2019.04.10
RESTFul 웹 서비스 관련  (0) 2019.04.10
RESTful (REpresentational State Transfer) API.  (0) 2016.04.07