import json
from django.views.generic import View
from rest_framework.views import APIView
from rest_framework.response import Response

from api import serializers
from webapp import models


class ArticleListView(APIView):
    def get(self, request, *args, **kwargs):
        articles = models.Article.objects.all()
        serializer = serializers.ArticleSerializer(articles, many=True)
        return Response(serializer.data, safe=False)


class ArticleCreateView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = serializers.ArticleSerializer(data=json.loads(request.body))

        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)

        return Response(serializer.errors, status=400)   
