Introduction to APIs in Python
Chris Ramakers
Engineering Manager
4xx
Client ErrorsResolution: Fix the request
5xx
Server ErrorsResolution: Should be fixed by the API administrator
4xx
Client Errors401 Unauthorized
- The request lacks valid authentication credentials for the requested resource404 Not Found
- Indicates that the server cannot find the resource that was requested429 Too Many Requests
- The client has sent too many requests in a given amount of time5xx
Server Errors500 Internal Server Error
- The server experienced an unexpected issue which prevents it from responding502 Bad Gateway
- The API server could not successfully reach another server it needed to complete the response504 Gateway Timeout
- The server (which acts as a gateway) did not get a response from the upstream server in timeimport requests url = 'http://api.music-catalog.com/albums' r = requests.get(url)
if r.status_code >= 400: # Oops, something went wrong
else: # All fine, let's do something # with the response
import requests
from requests.exceptions import ConnectionError
url = ''
try: r = requests.get(url) print(r.status_code)
except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.') print(error)
import requests
# 1: Import the requests library exceptions from requests.exceptions import ConnectionError, HTTPError
try:
r = requests.get("http://api.music-catalog.com/albums")
# 2: Enable raising exceptions for returned error statuscodes r.raise_for_status()
print(r.status_code)
# 3: Catch any connection errors except ConnectionError as conn_err: print(f'Connection Error! {conn_err}.')
# 4: Catch error responses from the API server except HTTPError as http_err: print(f'HTTP error occurred: {http_err}')
Introduction to APIs in Python