Consuming HTTP Services in Python Transcripts
Chapter: HTTP services with Python builtins
Lecture: Concept: Python 3's urllib

Login or purchase this course to watch this video and the rest of the course contents.
0:01 How do we use Python 3's urllib set of submodules to do basic get request against servers and even more advanced ones like post, put and delete?
0:12 Well, if we are going to do a get request we simply create
0:15 a get request against api/blog and this is going to give us all the blogs back as a json body; In code, we are going to need to import two modules,
0:24 urllib.request and json and then of course, we construct the url that we are going to work with, and we are going to call url open,
0:31 just like before, but this time, it's urllib.request.open and the response now supports working with context managers that is the with blocks,
0:42 so we don't have to be very careful about how and when we close the response, so again, we are going to check the response code,
0:49 read the text and there is no json feature so we are going to have to use the json module to load that back into a Python dictionary,
0:57 after that, we're done with the service, we are off to the races with plain old Python data.
1:03 So it gets pretty straightforward, but what about put or other modifying data operations,
1:08 so here we want to update a blog post, we want to do a put against api/blog/the id of the blog
1:14 and we are going to post as the body the changes we'd like to make to the post and what we'll get back is confirmation details, so in code again,
1:22 urllib request and json url but now we are going to create a dictionary that has all he data title, content and view count,
1:30 we are going to convert that to a json string via dump s and then, we need to pass actual bytes not a string,
1:36 so we are going to give it the utf8 representation of that string as bytes, okay, so that is the post data, let's go an throw in some headers,
1:46 so that we can say this is json you are going to be getting, and now, this time, instead of actually just calling url open and passing some values,
1:53 we are going to create a urllib.request.request object give it the url, the data, the headers, and now we can set in Python 3 the method to put,
2:01 so that is excellent, and then we carry on like before, we issue the request, check the response code read the text,
2:09 and turn that back into a dictionary, so this is how you work with urllib and Python 3's builtin http capabilities.


Talk Python's Mastodon Michael Kennedy's Mastodon