React & Django 프로젝트

input태그를 이용하여 직관적으로 한줄 노트를 작성할수 있는 앱

R&D (Backend) - DRF API 구현하기

장고 API 구현

URL METHOD Description Params Return
/api/notes/ GET 글 목록 X [..{ Notes }]
/api/notes/ POST 새로운 글 작성 (text)
/api/notes/{id} GET 글 상세보기 (Notes_id) { Note }
api/notes/{id} PATCH 글 수정 (Notes_id)
api/notes/{id} DELETE 글 삭제 (Notes_id)

notes app 생성

1
2
3
$ python manage.py startapp notes
# restframework install
$ pip install djangorestframework

app 추가

1
2
3
4
5
6
7
8
9
10
11
12
13
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# notes 앱 추가
'notes',
# rest framework 추가
'rest_framework',
]

models.py : 모델 구성

1
2
3
4
5
6
7
8
from django.db import models

class Notes(models.Model):
text = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now=False, auto_now_add=True)

def __str__(self):
return self.text

migrate

1
2
$ (venv) python manage.py makemigrations
$ (venv) python manage.py migrate

notes/serializers.py : 모델을 참조하여 구성

1
2
3
4
5
6
7
8
from rest_framework import serializers
from .models import Notes


class NoteSerializer(serializers.ModelSerializer):
class Meta:
model = Notes
fields = ("id", "text")

note/views.py : 실제 controller (serializer 참조)

1
2
3
4
5
6
7
8
9
10
11
12
13
from rest_framework import viewsets
from .serializers import NoteSerializer
from .models import Notes


class NoteViewSet(viewsets.ModelViewSet):
serializer_class = NoteSerializer

def get_queryset(self):
return Notes.objects.all().order_by("-created_at")

def perform_create(self, serializer):
serializer.save()

urls.py : API 라우팅

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# urls.py
from django.contrib import admin
from django.urls import path

from notes import urls
from django.conf.urls import include, url

urlpatterns = [
path("admin/", admin.site.urls),
url(r"^api/", include(urls))
]

---------------------------------

from django.conf.urls import url
from .views import NoteViewSet

# notes/urls.py
note_list = NoteViewSet.as_view({"get": "list", "post": "create"})

note_detail = NoteViewSet.as_view(
{"get": "retrieve", "patch": "partial_update", "delete": "destroy"}
)


urlpatterns = [
url("^notes/$", note_list, name="note-list"),
url("^notes/(?P<pk>[0-9]+)/$", note_detail, name="note-detail"),
]