Requests — how to tell if you're getting a success message?
Asked Answered
P

5

62

My question is closely related to this one.

I'm using the Requests library to hit an HTTP endpoint. I want to check if the response is a success.

I am currently doing this:

r = requests.get(url)
if 200 <= response.status_code <= 299:
    # Do something here!

Instead of doing that ugly check for values between 200 and 299, is there a shorthand I can use?

Planchette answered 6/11, 2017 at 19:46 Comment(0)
D
94

The response has an ok property. Use that:

if response.ok:
    ...

The implementation is just a try/except around Response.raise_for_status, which is itself checks the status code.

@property
def ok(self):
    """Returns True if :attr:`status_code` is less than 400, False if not.

    This attribute checks if the status code of the response is between
    400 and 600 to see if there was a client error or a server error. If
    the status code is between 200 and 400, this will return True. This
    is **not** a check to see if the response code is ``200 OK``.
    """
    try:
        self.raise_for_status()
    except HTTPError:
        return False
    return True
Disconcert answered 6/11, 2017 at 19:51 Comment(4)
Note that this counts the 3xx redirection range as okay, unlike the code in the question.Ectomere
I don't think you'll usually see a 300-range status anyway, since requests is going to follow the redirect. You'll get the status of the URL you were redirected to.Ashla
It won't follow redirects if you pass allow_redirects=FalseMarteena
I think also the problem with this might be 1xx responses, which won't raise for status and aren't in the range of code in the question either.Eutherian
S
14

I am a Python newbie but I think the easiest way is:

if response.ok:
    # whatever
Softcover answered 25/4, 2019 at 15:5 Comment(1)
Thuis duplicates the previous answer from 2017.Loris
M
11

The pythonic way to check for requests success would be to optionally raise an exception with

try:
    resp = requests.get(url)
    resp.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(err)

EAFP: It’s Easier to Ask for Forgiveness than Permission: You should just do what you expect to work and if an exception might be thrown from the operation then catch it and deal with that fact.

Manis answered 19/10, 2019 at 17:26 Comment(0)
P
2

HTTPStatus python docs

You can do that:

HTTPStatus(response.status_code).is_success
Pericles answered 24/4, 2024 at 6:56 Comment(1)
This is the most elegant way of doing it.Inter
T
-3

You could also do:

r = requests.get(url)
if response.status_code // 100 == 2:
    # Do something here!
Triphylite answered 13/3, 2023 at 10:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.