Programming/Django
REST API 서버 - 기본 세팅
코딩하는 포메라니안
2021. 4. 11. 17:38
0. API 서버용 Project와 app을 생성
Project 시작하기
1) 가상환경 켜기 $ python -m venv myvenv $ source myvenv/Scripts/activate 2) project 만들기 $ django-admin startproject staticproject 3) app 만들기 cd staticproject $ python manage.py startapp stati..
yerinpy73.tistory.com
1. Django Rest Framework 설치 및 설정
1) djangorestframework 패키지 설치
TERMINAL에 아래 명령어를 입력해줍니다.
pip install djangorestframework
2) settings.py 파일 수정
#settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cdpapp.apps.CdpappConfig',
'rest_framework',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
#API 권한 설정
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
]
}
2. Base 기능 구현하기 : GET, POST, PUT, DELETE
우선, 테스트를 위해 아래와 같은 코드를 작성한다.
#views.py
from django.shortcuts import render
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
def home(request):
return render(request, 'home.html')
class UserView(APIView):
"""
POST
"""
def post(self, request):
return Response("test ok", status=200)
"""
GET
"""
def get(self, request):
return Response("test ok", status=200)
"""
PUT
"""
def put(self, request):
return Response("test ok", status=200)
"""
DELETE
"""
def delete(self, request):
return Response("test ok", status=200)
#urls.py
from django.contrib import admin
from django.urls import path
import cdpapp.views
urlpatterns = [
path('admin/', admin.site.urls),
path('', cdpapp.views.home, name='home'),
path('api_server/', cdpapp.views.UserView.as_view(), name='api_server'),
]
python manage.py runserver
위의 명령어를 통해 서버를 실행시키면, 아래와 같은 결과를 볼 수 있다.
3. 테스트용 프로그램 실행
다른 어플이나 웹과 통신이 잘 되는지 확인하기 위해서 테스트용 프로그램[insomnia]을 설치하였다.
프로그램 설치는 insomnia.rest/download 이 사이트에서 진행하면 된다.
Download
Download Insomnia the best API Client for REST, GraphQL, GRPC and OpenAPI design tool for developers
insomnia.rest
사진 속 표시된 네모칸을 클릭한다.
local주소를 입력하고 [Send] 버튼을 클릭하면 Preview에 결과값이 나오는 것을 확인할 수 있다.