Skip to content

Instantly share code, notes, and snippets.

@marteinn
Last active January 21, 2024 06:57
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save marteinn/3785ff3c1a3745ae955c to your computer and use it in GitHub Desktop.
Save marteinn/3785ff3c1a3745ae955c to your computer and use it in GitHub Desktop.
Using the Fetch Api with Django Rest Framework

Using the Fetch Api with Django Rest Framework

Server

First, make sure you use the SessionAuthentication in Django. Put this in your settings.py

# Django rest framework
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication'
    ]
}

Client

Then start with including the getCookie method from the Django Docs.

Finally use the fetch method to call your endpoint.

var myData = {
    hello: 1
};

fetch("/api/v1/endpoint/5/", {
    method: "put",
    credentials: "same-origin",
    headers: {
        "X-CSRFToken": getCookie("csrftoken"),
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(myData)
}).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log("Data is ok", data);
}).catch(function(ex) {
    console.log("parsing failed", ex);
});

Easy! (Remember this will currently only work on Chrome and Firefox)

@dotapetro
Copy link

Thanks, it helped me!

@nhaggmark
Copy link

Thanks! Super helpful!

@dhicksNTIA
Copy link

You are a god amongst mortals. Thank you for this.

@budescode
Copy link

hi, can't I use get or post?
and must I use DRF?

@marteinn
Copy link
Author

@budescode This is a DRF example, but using fetch against regular Django is also possible, just not with this example code :)

Doing GET requests does not require anything special, doing POST does require a CSRF token and you'll need to pass it to your endpoint.

@vschmidt
Copy link

vschmidt commented Sep 6, 2019

To send data using the GET method you must construct the URL. The function below receives a URL and the data to be sent:

function montaURL(url,data) {
    params = Object.keys(data).reduce(function(_qs, k, i){ 
        if(data[k]){
            return _qs + '&' + k + '=' + data[k];
        }else{
            return _qs + '&' + k + '=';
        }
    }, '').substring(1);;
    url = url + "?" + params;
    return url
};

Can be used in a function as in the example:

data_to_get = {
        "id": 1,
        "name": "Test",
};    

function get_conta_receita(data_to_get = {}) {
    var myData =  {
        "id": data_to_get[\'id\'],
        "name": data_to_get[\'name\'],
    };        
    const defaults = {
        'method': 'GET',
        'credentials': 'include',
        'headers': new Headers({
          'X-CSRFToken': csrf_token,
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'X-Requested-With': 'XMLHttpRequest'
        }),
    };

    url = montaURL(contas_receita_api, myData);

    fetch(url, defaults)
    .then(function(response) {
        return response.json();      
    }).then(function(data) {
        console.log(data);
    }).catch(function(ex) {
        console.log("parsing failed", ex);
    });
};

@kc2684
Copy link

kc2684 commented Jun 10, 2021

Any chance of someone posting an example of the django code that receives "myData" and returns the "data"?
Thanks

@SatishChoudary
Copy link

data_to_get = {
"id": 1,
"name": "Test",
};

function get_conta_receita(data_to_get = {}) {
var myData = {
"id": data_to_get['id'],
"name": data_to_get['name'],
};
const defaults = {
'method': 'GET',
'credentials': 'include',
'headers': new Headers({
'X-CSRFToken': csrf_token,
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}),
};

url = montaURL(contas_receita_api, myData);

fetch(url, defaults)
.then(function(response) {
    return response.json();      
}).then(function(data) {
    console.log(data);
}).catch(function(ex) {
    console.log("parsing failed", ex);
});

};

@baramsivaramireddy
Copy link

Thanks, it helped me too .

@koljapluemer
Copy link

Finally, someone explaining this. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment