8. List
But of course, we will need to list all the books. We will do a GET where we list all the elements.
We create the appropriate tests.
# tests/libros/test_views.py
import pytest
from app.libros.models import Libros
@pytest.mark.django_db
def test_add_book(client):
# Given
libros = Libros.objects.all()
assert len(libros) == 0
# When
resp = client.post(
"/api/libros/",
{
"title": "El fin de la eternidad",
"genre": "Ciencia Ficción",
"author": "Isaac Asimov",
"year": "1955",
},
content_type="application/json"
)
# Then
assert resp.status_code == 201
assert resp.data["title"] == "El fin de la eternidad"
libros = Libros.objects.all()
assert len(libros) == 1
@pytest.mark.django_db
def test_get_single_book(client):
# Given
libro = Libros.objects.create(
title="El fin de la eternidad",
genre="Ciencia Ficción",
author="Isaac Asimov",
year="1955",
)
# When
resp = client.get(f"/api/libros/{libro.id}/")
# Then
assert resp.status_code == 200
assert resp.data["title"] == "El fin de la eternidad"
@pytest.mark.django_db
def test_get_single_book_incorrect_id(client):
# When
resp = client.get(f"/api/libros/-1/")
# Then
assert resp.status_code == 404
@pytest.mark.django_db # new
def test_get_all_books(client, faker): # <- note that 'faker' is added
# Given
def create_random_book():
return Libros.objects.create(
title=faker.name(),
genre=faker.job(),
author=faker.name_nonbinary(),
year=faker.year(),
)
libro_1 = create_random_book()
libro_2 = create_random_book()
# When
resp = client.get(f"/api/libros/")
# Then
assert resp.status_code == 200
assert resp.data[0]["title"] == libro_1.title
assert resp.data[1]["title"] == libro_2.title
We create the view.
# app/libros/views.py
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import LibroSerializer
from .models import Libros
def ping(request):
data = {"ping": "pong!"}
return JsonResponse(data)
class LibrosList(APIView):
def get(self, request): # new
libros = Libros.objects.all().order_by('created_at')
serializer = LibroSerializer(libros, many=True) # many=True to list
return Response(serializer.data, status=status.HTTP_200_OK)
def post(self, request):
serializer = LibroSerializer(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)
class LibrosDetails(APIView):
def get(self, request, pk):
libro = Libros.objects.filter(pk=pk).first()
if libro:
serializer = LibroSerializer(libro)
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(status=status.HTTP_404_NOT_FOUND)
There is no need to register a new route, since we will use the same one as POST, except that when using GET it will list the books.
You can run the test.
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.