Django는 초기에 프론트엔드와 백엔드를 모두 처리해주는 풀스택 프레임워크
-> 프론트엔드 기술의 발전과 함께 프론트와 백엔드를 분리하여 개발하는 것이 점차 선호되고, Django가 이를 적극 지원
이 때 등장한 것이 바로 'DRF'
DRF란?
- Django에서 RESTfulAPI를 구축하기 위한 도구로, 다양한 기능을 제고하여 효율적인 API개발을 가능케 함
- Django 프레임워크를 기반으로 하며 파이썬언어를 사용
DRF에서 제공하는 주요 기능
1) 직렬화(Serialization)
- 웹 애플리케이션에서 프론트엔드와 백엔드는 서로 다른 데이터 형식을 사용하므로 데이터를 주고받기 위해서는 데이터 형식을 일치시켜야 하는데, DRF가 데이터의 직렬화와 역직렬화 작업을 담당
(직렬화와 역직렬화를 쉽게 처리할 수 있는 Serializer클래스를 제공)
- 직렬화 : 서버에 있는 파이썬 객체 형식의 데이터를 JSON, XML, YAML 등의 형식으로 변환하는 것
- 역직렬화 : 반대로 JSON, XML, YAML 등의 형식 데이터를 파이썬 객체로 변환
=> 이러한 작업을 통해 프론트엔드와 백엔드 간의 데이터 통신을 가능하게 한다.
2) 뷰(View)
- Django 뷰 클래스와 유사하지만 HTTP메서드에 따라 해당 요청을 처리할 수 있는 함수 같은 RESTfulAPI에 적합한 기능들을 추가로 제공함
3) 인증과 권한 : DRF는 다양한 인증 및 권한 관리 방식들을 지원
SessionAuthentication
- 세션을 이용한 인증 방식이며 Django의 기본 세션 인증 방식.
- 클라이언트가 서버로 요청 보낼 때 세션 키를 함께 전송하여 인증
- 웹 브라우저와 서버 간에 쿠키를 이용하여 세션 정보를 저장하고, 활용하여 인증한다.
- RESTfulAPI를 개발할 때 권장되지 않음 (Stateless하지 않기 때문)
BasicAuthentication
- HTTP 기본 인증 방식으로, 클라이언트가 API 요청 헤더에 자신의 인증 정보를 담아서 전송
- 보안성이 낮음 (비추)
TokenAuthentication
- 인증 토큰을 사용하는 방식, 클라이언트가 로그인하면 서버에서 인증 토큰을 발급한다. 이후 클라이언트는 인증 토큰을 함께 요청 헤더에 넣어서 전송
JWTAuthentication
- JSON WEB Token 방식, JWT는 서버에서 인증 토큰 발급, 토큰을 클라이언트가 전송하면 서버에서 검증 후 인증해준다.
OAuth2Authentication
- OAuth2 프로토콜을 사용하는 방식. 클라이언트가 서버에 접근하는 권한을 부여받기 위해 인증과정을 거치는 방식
위 같이 다양한 인증방식을 지원하지만
Token Authentication 또는 JWT Authentication과 같이 사용자 인증을 위해 토큰을 사용하는 방식이 보다 안전!
4) 캐싱 : API 요청 결과를 캐싱하여 API 응답 속도를 향상
REST와 RESTful API란?
- Representational State Transfer를 기반으로한 웹 API 디자인 패턴
- 안전하고 효율적인 통신을 위해 API를 만들기 위한 규칙을 REST API, RESTful API라고 함
- RESTful API는 URL과 HTTP Method를 통해 데이터를 요청하고 응답하는 API
RESTful 규칙들
1) RESTful한 API를 만들려면 각 HTTP 메소드를 목적에 맞게 사용해야 한다.
GET | 데이터 조회 |
POST | 데이터 생성 |
PUT | 데이터 수정 |
PATCH | 특정 데이터 수정 |
DELETE | 특정 데이터 삭제 |
2) 요청의 결과에 따른 적절한 상태 코드 반환
def post(self, request):
serializer = ArticleSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
위 코드와 같이 데이터가 성공적으로 작성되면 201, 잘못된 요청일 경우 400과 같이 상태코드를 적절히 반환해야함
3) RESTful한 URL
- 명확하고 의미있는 URL 사용
- 코드의 재사용성과 유연성을 높일 수 있는 URL
- URL에 생성, 조회 등의 정보를 포함시키지 않기
- http://localhost:8000/article/create (x)
- http://localhost:8000/article (o)
- URL의 마지막에 슬래시(/)를 사용하지 않기
- 잘못 설계된 URL: http://localhost:8000/article/1/ (x)
- 잘 설계된 URL: http://localhost:8000/article/1 (o)
'Django' 카테고리의 다른 글
Django-rest-framework 01. 프로젝트 시작하기 (2) | 2023.04.25 |
---|---|
Django를 이용해서 화면 띄우기 (Django 맛보기) (0) | 2023.04.04 |
프레임워크 Django 기초 (0) | 2023.04.03 |