How to Get Response Status Code in Python Easily
Use the
requests library in Python and access the status_code attribute of the response object to get the HTTP status code. For example, response = requests.get(url) then response.status_code gives the status code.Syntax
To get the response status code in Python, first send an HTTP request using requests.get() or other HTTP methods. Then access the status_code attribute of the response object.
requests.get(url): Sends a GET request to the URL.response.status_code: Holds the HTTP status code returned by the server.
python
import requests response = requests.get('https://example.com') status = response.status_code print(status)
Output
200
Example
This example shows how to send a GET request to a website and print the HTTP status code returned by the server.
python
import requests url = 'https://httpbin.org/status/404' response = requests.get(url) print('Status code:', response.status_code)
Output
Status code: 404
Common Pitfalls
Some common mistakes when getting the status code include:
- Not importing the
requestslibrary before use. - Trying to get
status_codefrom a non-response object. - Ignoring exceptions if the request fails (e.g., network errors).
Always handle exceptions and ensure the response object is valid before accessing status_code.
python
import requests try: response = requests.get('https://invalid.url') print(response.status_code) # This will not run if request fails except requests.exceptions.RequestException as e: print('Request failed:', e)
Output
Request failed: HTTPSConnectionPool(host='invalid.url', port=443): Max retries exceeded with url: / (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x7f...>: Failed to resolve 'invalid.url'"))
Quick Reference
Summary tips for getting response status code in Python:
- Use
requests.get()or other HTTP methods to send requests. - Access
response.status_codeto get the HTTP status code. - Handle exceptions to avoid crashes on network errors.
- Status codes like 200 mean success, 404 means not found, 500 means server error.
Key Takeaways
Use the requests library and access response.status_code to get the HTTP status code.
Always handle exceptions to manage network or request errors gracefully.
Status codes indicate the result of the HTTP request, like 200 for success or 404 for not found.
Import requests before using it and ensure your response object is valid.
Print or use the status code to control your program flow based on server responses.