Consuming HTTP Services in Python Transcripts
Chapter: Consuming RESTful HTTP services
Lecture: Concept: updating a post with requests
Login or
purchase this course
to watch this video and the rest of the course contents.
0:01
In our service, to update a blog post, we are going to do an http put to the particular url
0:08
that represents that blog post, and the body of that post is going to contain the details in json form to replace the value on the server,
0:16
so we want to do a put/api/blog/id and pass the title and the content, things like that.
0:22
The response is going to be just an http status code 204, no content, everything worked, thank you. In code, what does that look like?
0:31
Well, we start by creating a dictionary that is going to be the body of our post,
0:34
so updated post details, we are going to pass title, content, view count and published. Now, not all of these necessarily changed, so it's up to you
0:42
and really up to the API to determine whether you have to pass all the values back
0:47
or just the ones that are changing, I believe the API we are working here
0:50
requires all the new values to be passed or it will like null them out on the server.
0:55
So, we are going to pass them all but it could be possible if you just want to change the title
0:59
you might just have to pass the title, that is up to the API. Then we come up with the post url that we are going to update,
1:06
API/blog the id of that post, and then what we do is we do a request.put, so we send a put request, or http request with a put verb to that url
1:15
and we pass the json body as the updated post details, remember, that is going to take the dictionary and convert it to a json string
1:22
and set the content type of the put to be application/json. And then of course we want to check the status code, and make sure that worked,
1:32
in our case, the contract we have with the servers 204 is good, everything else not good, but you might want to be on the lookout for 200 as well
1:39
if they not carefully managing their status codes in the response, and if that worked, then, yeey, we're all good, now we can just assume
1:46
that that post was updated as we specified.