Ads by ProfitSence
Close

Using the Fetch API with Django Rest Framework

Last Updated on Wednesday 5th Oct 2022

Server

			
					REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication'
    ]
}

			
	

Client

  • Then start with including the getCookie method from the Django Docs.{.ext}
  • 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);
});