Skip to content

Instantly share code, notes, and snippets.

@jechav
Forked from marteinn/info.md
Created July 31, 2017 03:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jechav/7f023409eaf1ce1e94d19828067355a9 to your computer and use it in GitHub Desktop.
Save jechav/7f023409eaf1ce1e94d19828067355a9 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)

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