Error handling

Introduction to APIs in Python

Chris Ramakers

Engineering Manager

Error status codes

4xx Client Errors


  • Indicate issues on the client's end
  • Common causes: Bad requests, authentication failures, etc ...

Resolution: Fix the request

5xx Server Errors


  • Arises from problems on the server
  • Common causes: Server overloaded, server configuration errors, internal errors

Resolution: Should be fixed by the API administrator

Introduction to APIs in Python

Error status codes: examples

4xx Client Errors


  • 401 Unauthorized - The request lacks valid authentication credentials for the requested resource
  • 404 Not Found - Indicates that the server cannot find the resource that was requested
  • 429 Too Many Requests - The client has sent too many requests in a given amount of time

5xx Server Errors


  • 500 Internal Server Error - The server experienced an unexpected issue which prevents it from responding
  • 502 Bad Gateway - The API server could not successfully reach another server it needed to complete the response
  • 504 Gateway Timeout - The server (which acts as a gateway) did not get a response from the upstream server in time
Introduction to APIs in Python

Handling errors

API errors

import 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

Connection errors

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)
Introduction to APIs in Python

raise_for_status()

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

Let's practice!

Introduction to APIs in Python

Preparing Video For Download...