Responses: Status Codes
What are HTTP status codes? Which status codes do exist? These questions are answered in this lesson of the Making HTTP Requests With Python course.
You’ll learn about the different status code ranges and what they mean internally.
Additionally, you’ll learn how to handle different status codes in multiple ways, e.g. by using
00:00 Status codes are issued by a server in response to a client request. Here’s a few examples. In the 100 series, it’s information. 200 series indicates success—like the request was received, understood, and accepted. 300 means a redirection. Somewhere in the 400 series means a client error, and the 500 series means a server error.
Response instance has a conditional expression inside of it that will evaluate to
True if the
.status_code is between
400—or it’ll just be
False, otherwise. So we can simplify our last script inside of the
We can run our script again after saving. And in this case, since it’s an invalid URL, it’s coming back with
An error has occurred. Change it back to the valid one—just getting rid of the statement here… and save. Let’s try running it again.
Okay. This looks a little bit cleaner.
from requests.exceptions we’re going to import
HTTPError. We’ll set up a
for loop—for a URL with the first API, which is the standard one that we’ve been using, and then we’ll have a second one, which is going to the invalid one. From there, inside the
for loop—oh, I need to put a colon on the end—we’ll
try and we’ll look at our
05:30 Note that f-strings are only available in Python 3.6 or higher. There are additional tutorials about using f-strings available on the Real Python site, so you can search there if you have questions about it.
Become a Member to join the conversation.