Consuming HTTP Services in Python Transcripts
Chapter: Consuming RESTful HTTP services
Lecture: Concept: Creating a post with requests

Login or purchase this course to watch this video and the rest of the course contents.
0:01 To create a post we do an http post, one is blog post one is a verb,
0:08 an http post against the general blog collection,
0:11 so we do an http post against api/blog and the body of that post is a json document
0:17 containing all the details we want to use as part of that post creation,
0:21 the title, the content, things like that.
0:24 Then what comes back is the actual thing that the server created,
0:28 so it inserted into the database, which generated things
0:30 like the id and other potential values
0:34 and it sent that back for us to continue to work with in our application.
0:37 Now, throughout the rest of these concepts in this chapter,
0:41 we are going to assume that we have always written import requests
0:45 and that the base url is that public url of our service
0:52 that will mean we just have a little less to look at at each of the detailed steps.
0:57 Okay, to create a new post, in code, what we are going to do is
1:00 we are going to create a new post dictionary and set the values
1:03 that we have control over, title, content, view count and published.
1:07 Remember, there is also id but that is server generated
1:10 so there is no point in passing it or trying to come up with one
1:13 because it's just going to be created by the database anyway,
1:15 then we set the url to be the base url/api/blog,
1:19 not a particular id, just the general collection, and then we are going to do
1:22 an http post to that url and the body is going to be the dictionary,
1:27 we say the json objects, the dictionary is going to be converted to json,
1:31 now, one note is I actually in my code when I did the demos,
1:35 I set the headers and set the body type, where the content type is json
1:40 actually if we set the json property request knows that that has to be the case
1:44 and it's going to set it for us so we can skip that header step it turns out.
1:48 Now, when we are done, we better check the response code,
1:51 the standard response code for some sort of post like this is 201 created,
1:55 so if it's not 201 that's a problem, but if it is, we can just access the data
2:00 by calling .json convert our server side post
2:05 into just a simple Python dictionary and we're off to the races.