Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 112fed5

Browse files
Instruction for adding an update JSON API
1 parent 6c8d7ab commit 112fed5

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

‎units/django/7/ajax.md‎

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,119 @@ Asynchronous HTTP Requests (Ajax)
44

55
In the [previous tutorial](https://github.com/kabirbaidhya/learn-python-django-web/blob/master/units/django/5/validation.md) we've covered the form validation part both in the frontend and the backend. In this tutorial we can use Async HTTP Requests or Ajax in our application.
66

7+
## Ajax Requests
8+
Ajax(Asynchronous JavaScript and XML) is a term to refer Asynchronous HTTP requests in the frontend world. It's asynchronous in the sense that, it provides a mechanism to send HTTP requests (from the client-side) to the server in the background without affecting/blocking the current page rendering or without having to reload the whole web page.
9+
10+
In this tutorial we'll be using Ajax requests to update the `completed` attribute of any todo item asynchronously without the whole page refresh, using JavaScript.
11+
12+
## Adding a JSON API endpoint
13+
Before we can send HTTP requests to the server, we need to create a new url endpoint in our django app to accept it. In this case we don't need to return any HTML data from the server as we just need to update the todo item on the server and return. So, here we'll create a url endpoint that accepts JSON data and responds with JSON too.
14+
15+
We'll be refering this new url endpoint as an API endpoint because it's different from the urls where HTML forms are synchronously submitted to or the urls where the users navigate directly, but instead it's just an API provided by the server to the client to do some operations based upon HTTP. So, we'll call it JSON API for now.
16+
17+
### Add a new view
18+
First, we'll add a new file `todos/views_api.py`. Here we will have a function `update` which will be responsible for handling our API request on the server.
19+
20+
```python
21+
import json
22+
from django.http import JsonResponse
23+
from django.views.decorators.csrf import csrf_exempt
24+
from django.views.decorators.http import require_http_methods
25+
26+
from todos.models import Todo
27+
28+
29+
@csrf_exempt
30+
@require_http_methods(['PATCH'])
31+
def update(request, id):
32+
# Get the params from the payload.
33+
data = json.loads(request.body.decode('utf-8'))
34+
35+
print('Received update API request for todo id: ', id)
36+
print('Completed: ', data['completed'])
37+
38+
# Update the model
39+
todo = Todo.objects.get(pk=id)
40+
todo.completed = data['completed']
41+
todo.save()
42+
43+
print('Todo item updated')
44+
45+
return JsonResponse({})
46+
47+
```
48+
49+
Here, we are using the HTTP `PATCH` method which might seem new to you as previously we're only used to `GET` and `POST` methods. We used `PATCH` here as this request will update our todo item partially which is as per the [HTTP spec](https://tools.ietf.org/html/rfc2068#section-19.6.1.1).
50+
51+
We'll learn more about HTTP methods and JSON based APIs in later tutorials on REST APIs.
52+
53+
### Add a new url
54+
Now that we've created a new view function, we'll create a new url for our update endpoint.
55+
56+
For this we'll make changes on our `todos/urls.py` file.
57+
```python
58+
from todos import views, views_api
59+
60+
urlpatterns = [
61+
...
62+
url(r'^edit/todos/(\d+)$', views.edit, name='edit'),
63+
64+
# API Route for Ajax
65+
url(r'^api/todos/(\d+)$', views_api.update, name='api_update_todo')
66+
]
67+
```
68+
69+
### Testing the API
70+
Now that our update API is ready to change the `completed` attribute of a todo item, we'll need to test it. For testing JSON based APIs or any HTTP APIs we can use tools like [postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en). It's a chrome web extension which you can install it on your chrome browser.
71+
72+
Go and install it first if you don't have it.
73+
74+
After you're done with installing, you can open the postman app.
75+
76+
Now in the postman, create a new tab and enter the following url:
77+
78+
```
79+
http://localhost:8000/api/todos/2
80+
```
81+
82+
I'm assuming you have already run the django dev server on port `8000`.
83+
84+
Also make sure you've provided the todo id of the todo item for which `completed` is `false`, so that we can test this API updates it to `true` with postman.
85+
86+
Now, since we're accepting only `PATCH` http method, set the method to `PATCH` from the dropdown near the url.
87+
88+
Our code above expects the request data to be JSON containing a boolean attribute `completed`.
89+
```python
90+
# Get the params from the payload.
91+
data = json.loads(request.body.decode('utf-8'))
92+
93+
print('Received update API request for todo id: ', id)
94+
print('Completed: ', data['completed'])
95+
96+
# Update the model
97+
todo = Todo.objects.get(pk=id)
98+
todo.completed = data['completed']
99+
```
100+
101+
So, we'll provide a json data in postman like this:
102+
```json
103+
{
104+
"completed": true
105+
}
106+
```
107+
108+
Set the body to be raw JSON, paste the above json object in the request body and hit the Send button.
109+
110+
Now after you see the success response (`200 OK`) you can go and refresh you app in the browser, you can see our todo item with `id=2` has been updated with the checkbox checked as we've set `completed=true`. Now go back to the postman and change completed to `false` and hit Send again.
111+
112+
Now, if you come back to your browser and refresh you'll find it's completed attribute has been updated again. Great.
113+
114+
You can test this API for other todo items too just by changing the `id` value in the url to something else like this:
115+
```
116+
http://localhost:8000/api/todos/5
117+
```
118+
119+
7120
## Source Code
8121
Check the full source code [here](https://github.com/kabirbaidhya/django-todoapp/tree/step-20).
9122

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /