Felhantering

Introduktion till API:er i Python

Chris Ramakers

Engineering Manager

Felstatuskoder

4xx Klientfel


  • Indikerar problem på klientens sida
  • Vanliga orsaker: Felaktiga förfrågningar, autentiseringsfel m.m.

Åtgärd: Korrigera förfrågan

5xx Serverfel


  • Uppstår vid problem på servern
  • Vanliga orsaker: Överbelastad server, konfigurationsfel, interna fel

Åtgärd: Bör åtgärdas av API-administratören

Introduktion till API:er i Python

Felstatuskoder: exempel

4xx Klientfel


  • 401 Unauthorized – Förfrågan saknar giltiga autentiseringsuppgifter för resursen
  • 404 Not Found – Servern kan inte hitta den efterfrågade resursen
  • 429 Too Many Requests – Klienten har skickat för många förfrågningar inom en given tidsperiod

5xx Serverfel


  • 500 Internal Server Error – Servern drabbades av ett oväntat fel som hindrar den från att svara
  • 502 Bad Gateway – API-servern kunde inte nå en annan server som krävdes för att slutföra svaret
  • 504 Gateway Timeout – Servern (som fungerar som gateway) fick inget svar från uppströmsservern i tid
Introduktion till API:er i Python

Hantera fel

API-fel

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

Anslutningsfel

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)
Introduktion till API:er i 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}')
Introduktion till API:er i Python

Nu kör vi en övning!

Introduktion till API:er i Python

Preparing Video For Download...