Responses: Content and Headers
When dealing with
requests we are mostly interested in the content we receive. In this lesson you’ll learn how to access the response content as well as the response meta information stored in the headers.
You can access the content of a response in three different ways and formats. Here is a quick overview about the different ways and formats:
content: This attribute returns the raw bytes of the response content
textattribute returns the content as a normal UTF-8 encoded Python string
json(): You can use the
json()method to get the response content in JSON format
headers attributes returns a Python dictionary with all of the response headers.
00:00 Next, let’s talk about the data that actually got sent back from the server that’s in the body of the response. I’m going to go ahead and close my script and expand my terminal back up here and clear it.
And what you might notice here at the very beginning of it is it saved an output in a byte format—the
b at the beginning here. What may be a little more human-friendly is to output it as text, so the
response.text, and you’ll see it’s just a text string then. But again, it’s still a lot of information and a little hard to look at.
These are all endpoints that we can go to to get a little more information, so we’re mainly just at the root of
github.com and its API. Another way to look at it is as JSON, and that saves it as a JSON dictionary.
01:30 In fact, what I want to do is be able to look at this a little bit easier, so I’m going to make a really simple function to kind of walk through this information and be able to share it with you in a more readable way.
All right, so we have a little function now that we can use called
print_d(). So, the first thing we need to do is take that response and save it into—let’s just call it the JSON version of the response,
That’s a little more readable. We can see the pairs. So, the
current_user_url—and that would be the
api.github.com/user—the commit searching, the emails URL, stuff for emojis, and so forth. A little bit easier to walk through. In fact, we could look at any of these pairs directly if we wanted to. Let’s say we want to look at the
02:56 We can access any of them directly just by putting in the particular key. If we need a little bit more information, like metadata about the response, we can take a look at the response’s headers.
Something that’s special about this dictionary object is that since it’s part of the HTTP spec, that means that all these headers are case insensitive. So if we want to access any of them directly, we can access
'Content-Type'. In this case, again, we mentioned earlier that it’s JSON, but let’s look at it again.
Become a Member to join the conversation.