In attempting to send a POST request to an API, a 403 Forbidden response is being returned. I'm using SessionAuthentication that comes along with Django Rest Framework as the means of API authentication.
The csrftoken variable in the script is in fact assigned the Django{% csrf_token %} that is contained in the DOM. I also confirmed that the request_method variable is POST. What would be causing the 403 to be raised in this case?
let bookmark = document.querySelector("polygon[id*=bookmark]");
var csrftoken = Cookies.get("csrftoken");
bookmark.addEventListener("click", function(event) {
let request_method;
let bookmark = this.getAttribute("fill");
if (bookmark === "white") {
request_method = "post";
} else {
request_method = "delete";
}
const [post, id] = this.id.split("_");
const request = new Request(
`http://localhost:8000/api/v1/bookmarks/${id}/`, {
'method': request_method,
"Content-Type": "application/json",
"Accept": "application/json",
'X-CSRFToken': csrftoken
}
);
fetch(request).then(response => {
if (response.status === 201) {
this.setAttribute("fill", "gold");
} else {
this.setAttribute("fill", "white");
}
})
})
bookmark_api_patterns = ([
path("<int:id>/", posts_api.BookmarkedPostEndpoint.as_view(), name="bookmark")
], "posts")
urlpatterns = [
path("api/v1/bookmarks/", include(bookmark_api_patterns, namespace="api_bookmarks"))
]
class BookmarkedPostEndpoint(APIView):
def post(self, request, id):
question = Question.objects.get(id=id)
bookmark = Bookmark.objects.create(
question=post, profile=request.user.profile
)
return Response(status=HTTP_201_CREATED)
def delete(self, request, id):
question = Question.objects.get(id=id)
bookmark = Bookmark.objects.get(question=question)
bookmark.delete()
return Response(status=HTTP_204_NO_CONTENT)