rest API added

This commit is contained in:
Peter Kotyczka 2024-04-17 21:19:48 +02:00
parent 656d206552
commit 8a7c9844cd
5 changed files with 51 additions and 52 deletions

View File

@ -52,6 +52,11 @@ MIDDLEWARE = [
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:8000',
)
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
@ -139,3 +144,5 @@ STATIC_URL = 'static/'
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

View File

@ -33,5 +33,3 @@ def api_home(request,endpoint, params={"message": "Your JSON Repsonse"}):
return JsonResponse(data)
##return JsonResponse()

View File

@ -1,13 +1,9 @@
from django.urls import path,include
from rest_framework import routers
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
router = routers.DefaultRouter()
router.register(r'item', views.ShoppingItemList)
router.register(r'product', views.ProductList)
from pyapp_api import views
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
path('items/', views.item_list),
path('items/<int:pk>/', views.item_detail),
]

View File

@ -1,54 +1,52 @@
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.decorators import api_view
from django.http.response import JsonResponse
from rest_framework.parsers import JSONParser
from rest_framework.response import Response
from rest_framework import status, permissions, viewsets
from rest_framework import permissions
from pyapp.models import ShoppingItem, Product
from .serializers import ShoppingItemSerializer, ProductSerializer
class ShoppingItemList(viewsets.ModelViewSet):
@api_view(['GET', 'POST'])
def item_list(request):
"""
API endpoint that allows users to be viewed or edited.
List all ShoppingItems, or create a new snippet.
"""
queryset = ShoppingItem.objects.all().order_by('name')
serializer_class = ShoppingItemSerializer
permission_classes = [permissions.AllowAny]
if request.method == 'GET':
ShoppingItems = ShoppingItem.objects.all()
serializer = ShoppingItemSerializer(ShoppingItems, many=True)
return Response(serializer.data)
class ProductList(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Product.objects.all().order_by('title')
serializer_class = ProductSerializer
permission_classes = [permissions.IsAuthenticated]
class ShoppingListApi(APIView):
# add permission to check if user is authenticated
permission_classes = [permissions.IsAuthenticated]
# 1. List all
def get(self, request, *args, **kwargs):
'''
List all the todo items for given requested user
'''
ShoppingItemList = ShoppingItem.objects.filter(user = request.user.id)
serializer = ShoppingItemSerializer(ShoppingItemList, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
# 2. Create
def post(self, request, *args, **kwargs):
'''
Create the ShoppingItem with given todo data
'''
data = {
'name': request.data.get('name'),
'price': request.data.get('price'),
'quantity': request.data.get('quantity'),
'done': False
}
serializer = ShoppingItemSerializer(data=data)
elif request.method == 'POST':
serializer = ShoppingItemSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def item_detail(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
ShoppingItems = ShoppingItem.objects.get(pk=pk)
except ShoppingItem.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = ShoppingItemSerializer(ShoppingItem)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = ShoppingItemSerializer(ShoppingItem, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
ShoppingItem.delete()
return Response(status=status.HTTP_204_NO_CONTENT)