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, an http post against the general blog collection,
0:12
so we do an http post against api/blog and the body of that post is a json document
0:18
containing all the details we want to use as part of that post creation, the title, the content, things like that.
0:25
Then what comes back is the actual thing that the server created, so it inserted into the database, which generated things
0:31
like the id and other potential values and it sent that back for us to continue to work with in our application.
0:38
Now, throughout the rest of these concepts in this chapter, we are going to assume that we have always written import requests
0:46
and that the base url is that public url of our service http://consumer_services_api.talkpython.fm
0:53
that will mean we just have a little less to look at at each of the detailed steps. Okay, to create a new post, in code, what we are going to do is
1:01
we are going to create a new post dictionary and set the values that we have control over, title, content, view count and published.
1:08
Remember, there is also id but that is server generated so there is no point in passing it or trying to come up with one
1:14
because it's just going to be created by the database anyway, then we set the url to be the base url/api/blog,
1:20
not a particular id, just the general collection, and then we are going to do an http post to that url and the body is going to be the dictionary,
1:28
we say the json objects, the dictionary is going to be converted to json, now, one note is I actually in my code when I did the demos,
1:36
I set the headers and set the body type, where the content type is json actually if we set the json property request knows that that has to be the case
1:45
and it's going to set it for us so we can skip that header step it turns out. Now, when we are done, we better check the response code,
1:52
the standard response code for some sort of post like this is 201 created,
1:56
so if it's not 201 that's a problem, but if it is, we can just access the data by calling .json convert our server side post
2:06
into just a simple Python dictionary and we're off to the races.