I am using Django REST framework to have data available in JSON and using them to refresh the page via AJAX. How can I secure the URL that page is being updated with data and no one can access the API url. The url is visible in AJAX in html so it can be accessed but I would like to prevent it by token or any other proper authentication that only access to it has website.
The URL is '/api/item/' (see in the AJAX code)
serializers.py
from rest_framework import serializers
from .models import Item
class ItemModelSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = [
'title',
'value',
]
views.py (in API)
from rest_framework import generics
from .serializers import ItemModelSerializer
from .models import Item
class ItemListAPIView(generics.ListAPIView):
serializer_class = ItemModelSerializer
def get_queryset(self):
return Item.objects.all().order_by('sort')
urls.py
urlpatterns = [
#...urls...
url(r'^api/item/', include('apps.item.api.urls', namespace='api-item')),
url(r'^admin/', admin.site.urls),
]
template - ajax
setInterval(function() {
$.ajax({
method: "GET",
url: "/api/item/",
success: function(data) {
$("#items tbody").empty();
$.each(data, function (key, value) {
var itemKey = key;
var itemTitle = value.title;
var itemValue = value.value;
$("#items tbody").append(
"<tr><td class='left'>" + itemTitle + "</td><td>" + itemValue</td></tr>"
)
})
},
error: function(data) {
console.log("error")
console.log(data)
}
})
}, 3000)