I am using the requests library to make requests to an API. However, I am not sure how to handle different status codes. I am particularly interested in handling status code 500, as that is part of my task.
1: Is a try/except block like I have an acceptable way of handling error codes?
2: How should I handle 500 status code? Would retrying 5 times once per second, then exiting be acceptable? If so, I don't know how to implement that without wrapping the whole function in a for loop (which seems bad practice).
Here is my function that makes HTTP requests:
def make_request(type, endpoint, h, data=None):
try:
url = f'https://example.net/not-important/{endpoint}'
if type == 'GET':
r = requests.get(url, headers=h)
elif type == 'POST':
r = requests.post(url, headers=h, json=data)
# r = requests.get('https://httpstat.us/500')
r.raise_for_status()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 500:
# 500 logic here. retry?
else:
print(f'An error occurred: {e}\n{e.response.status_code}')
sys.exit(1)
else:
return r.json()
Thank you!