I'm having some issues getting an index view working. When the database query returns a list of objects, it's all good. But when the query comes empty — because there are no records yet — the response isn't quite what I expect:
if request.method == 'GET':
powers = Power.objects.get(hero=hero_id);
if powers:
serializer = PowerSerializer(powers)
return Response(serializer.data)
context = {"message": "This hero has no powers... yet!"}
return Response(context, status=status.HTTP_200_OK)
The above code works flawlessly when a hero has powers. But when the hero has no powers, I expect to see the custom message but I'm instead getting HTTP 404 Not Found
. I tried changing to status=status.HTTP_204_NO_CONTENT
but, no difference — the same 404
pops up. Since I've never developed an API before, I'm not quite sure if this is how things should work.
I've combed the documentation and all I've found is how to handle one resource that doesn't exist — using return Response(status=status.HTTP_404_NOT_FOUND)
. So how do I handle a list of multiple resources that don't exist?
Please advise.