Computer Science/BackEnd

Django for APIs | #5 blog API

토마토. 2022. 9. 30. 19:35
chapter 5
Blog API

Django REST Framework로 Blog API를 만들어보자!

Blog API에는 User, permissions, CRUD로 구성할 것이다. 

또한, viewsets, routers, documentation도 살펴보자. 

 

Initial Set Up
(blogapi) $ django-admin startproject blog_project .
(blogapi) $ python manage.py startapp posts

 

INSTALLED_APPS = [
    'posts.apps.PostsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

 

Model
from django.db import models
from django.contrib.auth.models import User

# Create your models here.


class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)
    body = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

 

 

$ python manage.py makemigrations posts
Migrations for 'posts':
  posts/migrations/0001_initial.py
    - Create model Post

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, posts, sessions
Running migrations:
  Applying posts.0001_initial... OK

 

from django.contrib import admin
from .models import Post

# Register your models here.

admin.site.register(Post)

 

$ python manage.py createsuperuser
Username (leave blank to use 'tomato'): enkeejuniour
Email address: enk@naver.com
Password: 
Password (again): 
Superuser created successfully.

 

 

Tests
from django.test import TestCase
from django.contrib.auth.models import User

from .models import Post

# Create your tests here.


class BlogTests(TestCase):
    @classmethod
    def setUpTestData(cls):
        testuser1 = User.objects.create_user(
            username='testuser1',
            password='abc123'
        )
        testuser1.save()
        test_post = Post.objects.create(
            author=testuser1,
            title='Blog title',
            body='Body content...'
        )
        test_post.save()

    def test_blog_content(self):
        post = Post.objects.get(id=1)
        author = f'{post.author}'
        title = f'{post.title}'
        body = f'{post.body}'
        self.assertEqual(author, 'testuser1')
        self.assertEqual(title, 'Blog title')
        self.assertEqual(body, 'Body content...')

 

$ python manage.py test
Found 1 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.
----------------------------------------------------------------------        
Ran 1 test in 0.367s

OK
Destroying test database for alias 'default'...

 

Django REST Framework
INSTALLED_APPS = [
    'rest_framework',
    'posts.apps.PostsConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
    ]
}

 

URLs
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('api/v1/', include('posts.urls')),
    path('admin/', admin.site.urls),
]

API를 버전화하기 api/v1/, api/v2/ 처럼! 

 

from django.urls import path

from .views import PostList, PostDetail

urlpatterns = [
    path('<int:pk>/', PostDetail.as_view()),
    path('', PostList.as_view()),
]

 

 

Serializers

- JSON으로 변환

- 어떤 필드를 사용할지 지정

from rest_framework import serializers
from .models import Post


class PostSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ('id', 'author', 'title', 'body', 'created_at',)
        model = Post

serializer를 customize할 수 있다. => 더 찾아보기

 

 

Views
from rest_framework import generics
from .models import Post
from .serializers import PostSerializer

# Create your views here.


class PostList(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer


class PostDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

Django REST Framework에 있는 generics

ListAPIView -> read-only endpoint

RetrieveAPIView -> read-only endpoint

ListCreateAPIView -> write

RetrieveUpdateDestroyAPIView -> update, delete, read

 

Browsable API

 

 

 

Conclusion

permission 설정 필요