Let us explore what the function entails and how we can use it.
What is the ok function?
We use the ok() function to return a Boolean True if the status code of a given request is less than 400. If the status code exceeds 400, the function returns a false Boolean.
Although this is a relatively simple function, it provides extensible features that can perform different actions based on the returned value.
Examples
The following example shows how to use the response.ok() function.
response = requests.get('http://geekbits.io')
print(response.ok)
Running the code above should return the output as shown:
In this case, the request above returns a status code of 200 OK, meaning that the function will return a Boolean true.
If the response returns a 404 status code, the function will return a Boolean false, as shown in the example below:
response = requests.get('http://geekbits.io/77')
print(response.ok)
In this case, we are requesting a non-existing address. This returns a Not Found message. The resulting function output is as shown:
We can also use the output of the function to create conditional operations. An example is as shown:
response = requests.get('http://geekbits.io/77')
if response.ok:
print(response.status_code)
print(response.headers)
else:
print(response.status_code)
print("Address not found")
In the example above, we use an if block to show the status code and the response headers if the function is true. Otherwise, we return the status code and a custom message.
Running the code above should return:
Address not found
The output above returns a 404 status code and a custom message as defined in the else block.
If we change the code to a valid address, the code should return:
response = requests.get('http://geekbits.io/')
if response.ok:
print(response.status_code)
print(response.headers)
else:
print(response.status_code)
print("Address not found")
Resulting output:
{'Connection': 'keep-alive', 'Content-Length': '15618', 'Server': 'openresty', 'Content-Type': 'text/html; charset=utf-8', 'Status': '200 OK', 'content-encoding': 'gzip', 'x-request-id': '76ac0ad2c0e217ca11cda75097dd924b, 76ac0ad2c0e217ca11cda75097dd924b', 'etag': 'W/"1afd9-WY+Kkld5C7GYWexzRx0o8Oscw9M"', 'Ghost-Cache': 'MISS', 'Cache-Control': 'public, max-age=0', 'Ghost-Age': '0', 'Via': '1.1 varnish, 1.1 varnish', 'Accept-Ranges': 'bytes', 'Date': 'Thu, 15 Sep 2022 08:51:49 GMT', 'Age': '4774', 'X-Served-By': 'cache-ams21047-AMS, cache-jnb7024-JNB', 'X-Cache': 'MISS, HIT', 'X-Cache-Hits': '0, 2', 'X-Timer': 'S1663231909.077988,VS0,VE0', 'Vary': 'Accept-Encoding, Cookie', 'Ghost-Fastly': 'true', 'Alt-Svc': 'clear'}
Conclusion
In this article, you learned how to use the request.ok method to check if a status code is less than 400.