diff --git a/books/serializer.py b/books/serializer.py new file mode 100644 index 0000000..bec4902 --- /dev/null +++ b/books/serializer.py @@ -0,0 +1,12 @@ +from books.models import Book +from books.types import SerializedBook + + +def serialize_book(book: Book) -> SerializedBook: + return { + "title": book.title, + "author_full_name": book.author_full_name, + "year_of_publishing": book.year_of_publishing, + "copies_printed": book.copies_printed, + "short_description": book.short_description, + } diff --git a/books/types.py b/books/types.py new file mode 100644 index 0000000..76eaf10 --- /dev/null +++ b/books/types.py @@ -0,0 +1,9 @@ +from typing import TypedDict + + +class SerializedBook(TypedDict): + title: str + author_full_name: str + year_of_publishing: int + copies_printed: int + short_description: str diff --git a/books/views.py b/books/views.py index 91ea44a..c9cf17e 100644 --- a/books/views.py +++ b/books/views.py @@ -1,3 +1,13 @@ from django.shortcuts import render +from django.http import HttpResponse, JsonResponse +from django.views import View -# Create your views here. +from books.models import Book +from books.serializer import serialize_book + + +class Get_All_Books_Json_View(View): + def get(self, request: HttpResponse) -> JsonResponse: + books = Book.objects.all() + books_json = [serialize_book(book) for book in books] + return JsonResponse(data={'data': books_json}) diff --git a/bookshelf/urls.py b/bookshelf/urls.py index dfc7362..6b8bc13 100644 --- a/bookshelf/urls.py +++ b/bookshelf/urls.py @@ -1,6 +1,9 @@ from django.contrib import admin from django.urls import path +from books.views import Get_All_Books_Json_View + urlpatterns = [ path('admin/', admin.site.urls), + path('api/books/', Get_All_Books_Json_View.as_view()), ]