✅ 1. Install Django REST Framework
Pastikan proyek Django sudah dibuat, lalu install DRF:
pip install djangorestframework
Tambahkan 'rest_framework' ke INSTALLED_APPS di settings.py:
# settings.py INSTALLED_APPS = [ ... 'rest_framework', 'main', # app kamu ]
# main/models.py from django.db import models class Artikel(models.Model): judul = models.CharField(max_length=200) isi = models.TextField() tanggal_dibuat = models.DateTimeField(auto_now_add=True) def __str__(self): return self.judul
Migrasikan model:
python manage.py makemigrations python manage.py migrate
# main/serializers.py from rest_framework import serializers from .models import Artikel class ArtikelSerializer(serializers.ModelSerializer): class Meta: model = Artikel fields = '__all__'
# main/views.py from rest_framework import viewsets from .models import Artikel from .serializers import ArtikelSerializer class ArtikelViewSet(viewsets.ModelViewSet): queryset = Artikel.objects.all() serializer_class = ArtikelSerializer
# main/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ArtikelViewSet
router = DefaultRouter()
router.register(r'artikel', ArtikelViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Dan pastikan URL main/urls.py di-include di project/urls.py:
# project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('main.urls')), # base endpoint: /api/artikel/
]
python manage.py runserver
Akses di browser atau Postman:
GET /api/artikel/ → lihat semua artikel
POST /api/artikel/ → tambah artikel
GET /api/artikel/<id>/ → lihat satu artikel
PUT /api/artikel/<id>/ → update artikel
DELETE /api/artikel/<id>/ → hapus artikel
Copyright PythonesiaORG 2023
Komentar (0)