Now, we will compose and send an HTTP request to create a new toy:
http POST :8000/toys/ name="PvZ 2 puzzle" description="Plants vs
Zombies 2 puzzle" toy_category="Puzzle" was_included_in_home=false
release_date="2017-10-08T01:01:00.776594Z"
The following is the equivalent curl command. It is very important to use the -H "Content-Type: application/json" option to indicate to curl that it should send the data specified after the -d option as application/json instead of the default application/x-www-form-urlencoded:
curl -iX POST -H "Content-Type: application/json" -d '{"name":"PvZ
2 puzzle", "description":"Plants vs Zombies 2 puzzle",
"toy_category":"Puzzle", "was_included_in_home": "false",
"release_date": "2017-10-08T01:01:00.776594Z"}'
localhost:8000/toys/
The previous commands will compose and send the following HTTP request: POST http://localhost:8000/toys/ with the following JSON key-value pairs:
{ "name": "PvZ 2 puzzle", "description":"Plants vs Zombies 2 puzzle", "toy_category":"Puzzle", "was_included_in_home": "false", "release_date": "2017-10-08T01:01:00.776594Z" }
The request specifies /toys/, and therefore, it will match the '^toys/$' regular expression and run the views.toy_list function, that is, the toy_detail function declared within the toys/views.py file. The function just receives request as a parameter because the URL pattern doesn't include any parameters. As the HTTP verb for the request is POST, the request.method property is equal to 'POST', and therefore, the function will execute the code that parses the JSON data received in the request. Then, the function creates a new Toy and, if the data is valid, it saves the new Toy to the toys_toy table in the SQLite database. If the new Toy was successfully persisted in the database, the function returns an HTTP 201 Created status code and the recently persisted Toy serialized to JSON in the response body. The following lines show an example response for the HTTP request, with the new Toy object in the JSON response:
HTTP/1.0 201 Created Content-Length: 171 Content-Type: application/json Date: Tue, 10 Oct 2017 16:27:57 GMT Server: WSGIServer/0.2 CPython/3.6.2 X-Frame-Options: SAMEORIGIN { "description": "Plants vs Zombies 2 puzzle", "name": "PvZ 2 puzzle", "pk": 4, "release_date": "2017-10-08T01:01:00.776594Z", "toy_category": "Puzzle", "was_included_in_home": false }