Introduktion till API:er i Python
Chris Ramakers
Engineering Manager
4xx KlientfelÅtgärd: Korrigera förfrågan
5xx ServerfelÅtgärd: Bör åtgärdas av API-administratören
4xx Klientfel401 Unauthorized – Förfrågan saknar giltiga autentiseringsuppgifter för resursen404 Not Found – Servern kan inte hitta den efterfrågade resursen429 Too Many Requests – Klienten har skickat för många förfrågningar inom en given tidsperiod5xx Serverfel500 Internal Server Error – Servern drabbades av ett oväntat fel som hindrar den från att svara502 Bad Gateway – API-servern kunde inte nå en annan server som krävdes för att slutföra svaret504 Gateway Timeout – Servern (som fungerar som gateway) fick inget svar från uppströmsservern i tidimport requests url = 'http://api.music-catalog.com/albums' r = requests.get(url)if r.status_code >= 400: # Oops, something went wrongelse: # All fine, let's do something # with the response
import requestsfrom requests.exceptions import ConnectionErrorurl = ''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, HTTPErrortry: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