Vardhan Mahajan
Vardhan Mahajan

Reputation: 113

Rest API call returning forbidden

I am trying to get some data by calling a rest API but it's not working and returning:

Forbidden: /api/networthchart/data/

My view/API call: (Please ignore the print functions, I was using those for testing, but I left them in here just in case)

class networthChart(APIView, View):  
    authentication_classes = []
    permission_classes = []
    
    def get(self, request, format=None):
        print("its working")
        labels = []
        default_items = []

        if not self.request.user.is_active:
           return HttpResponseForbidden("Not signed in") # any error you want to display    
        else:
            print("user signed in")
            
        user = self.request.user
        networth_history = user.networthTracker.objects.filter(user = user)
        
        queryset = networth_history.order_by("date")
        print("questset gotten")
        
        for query in queryset:
            default_items.append(query.networth)
            labels.append(query.date)
            print("adding")
        
        print(labels)
        print(default_items)
        
        data = {
            "labels" : labels,
            "default" : default_items,
        }
        return Response(data)

and the JS is:

<script>
$(document).ready(function(){
  var endpoint = '/api/networthchart/data/'
  var defaultData = []
  var labels = []
  
  $.ajax({
    method:"GET",
    url: endpoint,
    success: function(data){
      labels = data.labels
      defaultData = data.default
      var ctx = document.getElementById('myChart').getContext('2d');
      var myChart = new Chart(ctx, {
          type: 'bar',
          data: {
              labels: labels,
              datasets: [{
                  label: '# of Votes',
                  data: defaultData,
                 #there was other stuff in here like bg colour and but I removed it for the sake of saving your time.
      });
    },
    error: function(errordata){
        console.log(errordata)
    }
  })
}

})
</script>

If you want more info on the error, it says,

"GET /user/ HTTP/1.1" 200 11730 its working Forbidden: /api/networthchart/data/ [29/Jan/2021 20:42:39] "GET /api/networthchart/data/ HTTP/1.1" 403 13

I don't understand why it's forbidden and what should I do to make this work?

The given solution:

<script>
'X-CSRFToken': csrftoken
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

$(document).ready(function(){ ........

Upvotes: 0

Views: 223

Answers (1)

04k
04k

Reputation: 175

The response is 403 because django requires a csrf token. In your JS file data's add

'X-CSRFToken': csrftoken
data: {
     'X-CSRFToken': csrftoken,
     labels: labels,
       datasets: [{
       label: '# of Votes',
       data: defaultData,
      }

where csrftoken is

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
const csrftoken = getCookie('csrftoken');

Upvotes: 1

Related Questions