Skip to content

Instantly share code, notes, and snippets.

@marteinn
Last active January 21, 2024 06:57
Show Gist options
  • Select an option

  • Save marteinn/3785ff3c1a3745ae955c to your computer and use it in GitHub Desktop.

Select an option

Save marteinn/3785ff3c1a3745ae955c to your computer and use it in GitHub Desktop.

Revisions

  1. marteinn revised this gist Jul 17, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion info.md
    Original file line number Diff line number Diff line change
    @@ -15,7 +15,7 @@ REST_FRAMEWORK = {
    ## Client
    Then start with including the getCookie method from the [Django Docs](https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax).

    Finally use the fetch method to call your endpoint.
    Finally use the `fetch` method to call your endpoint.

    ```javascript
    var myData = {
  2. marteinn revised this gist Jul 17, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion info.md
    Original file line number Diff line number Diff line change
    @@ -40,4 +40,4 @@ fetch("/api/v1/endpoint/5/", {
    });
    ```

    Easy!
    Easy! (Remember this will currently only work on Chrome and Firefox)
  3. marteinn revised this gist Jul 17, 2015. 1 changed file with 0 additions and 1 deletion.
    1 change: 0 additions & 1 deletion info.md
    Original file line number Diff line number Diff line change
    @@ -37,7 +37,6 @@ fetch("/api/v1/endpoint/5/", {
    console.log("Data is ok", data);
    }).catch(function(ex) {
    console.log("parsing failed", ex);
    alert("Error!");
    });
    ```

  4. marteinn created this gist Jul 17, 2015.
    44 changes: 44 additions & 0 deletions info.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    # Using the Fetch Api with Django Rest Framework

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

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

    ## Client
    Then start with including the getCookie method from the [Django Docs](https://docs.djangoproject.com/en/1.8/ref/csrf/#ajax).

    Finally use the fetch method to call your endpoint.

    ```javascript
    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);
    alert("Error!");
    });
    ```

    Easy!