django REST framework에서의 페이지
Django REST framework를 사용하다.
졸업작품을 만들기 위해서 REST한 api를 만들어야 할 일이 생겼다. 미루고 미루던 Django를 배울 겸 이번 프로젝트는 Django를 사용하기로 했는데, Django REST framework라는 걸 많이 이용하여 api를 제작한다고 하여 나도 사용해보기로 했다.
그런데 만들다가 든 의문
일단 튜토리얼 따라서 serializers
와 models
를 만들고 라우팅을 해 준 다음에 실행시키니 템플릿 페이지가 나왔다. api를 테스트 해 볼 수 있는 HTML Form과 각각의 Method에 따른 응답 결과를 보여주는 페이지었다. 굉장히 유용하긴 했는데, 여기서 든 의문점이 ‘이런 게 뜨면 ajax로 받아 올 땐 이거 클라이언트에서 다 처리해 줘야 하나?’ 였다.
결론은 아니었다. cUrl을 이용해서 요청을 날려봤다.
curl -X GET localhost:8000/api/
응답은 다음과 같다:
[
{
"first_name":"Suho",
"last_name":"Lee",
"image":"http://localhost:8000/media/img/media/default_image.jpg"
},
{
"first_name":"Suho2",
"last_name":"Lee3",
"image":"http://localhost:8000/media/img/media/default_image.jpg"
},
{
"first_name":"llll",
"last_name":"eeee",
"image":"http://localhost:8000/media/img/cat_profile.jpg"
}
]
이렇게 json만 오는 것이었다.
어? 그러면 브라우저인 건 어떻게 인식하고 띄우는거지? User Agent
때문인가? 싶어 다음과 같이 날려봤다
curl -H "User-Agent: Mozilla/5.0 (X11; Linux x86_64)\
AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/71.0.3578.98 Safari/537.36" -X GET localhost:8000/api/
응답은 다음과 같다:
[
{
"first_name":"Suho",
"last_name":"Lee",
"image":"http://localhost:8000/media/img/media/default_image.jpg"
},
{
"first_name":"Suho2",
"last_name":"Lee3",
"image":"http://localhost:8000/media/img/media/default_image.jpg"
},
{
"first_name":"llll",
"last_name":"eeee",
"image":"http://localhost:8000/media/img/cat_profile.jpg"
}
]
그럼 Accept
문제인가? Accept
를 달아봤다.
curl -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\
image/webp,image/apng,*/*;q=0.8" -X GET localhost:8000/api/
응답은 변함없었다. 그럼 남은 건 하나다. User-Agent
와 Accept
를 둘 다 보는 거다. cUrl
로 날려봤다.
curl -H "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,\
image/webp,image/apng,*/*;q=0.8; User-Agent: Mozilla/5.0\
(X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)\
Chrome/71.0.3578.98 Safari/537.36" -X GET localhost:8000/api/
응답은 다음과 같다:
!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="robots" content="NONE,NOARCHIVE" />
<title>Api Root – Django REST framework</title>
...
제대로 답변이 온다.
결론
Django REST framework를 이용할 때 html이 오는 경우는 헤더에 UA
와 Accept
가 동시에 있는 경우이다. 일반적으로 사용할 때는 문제 없으니 안심.
Comments