Úvod do API v Pythonu
Chris Ramakers
Engineering Manager
4xxŘešení: Opravit požadavek
5xxŘešení: Řeší správce API
4xx401 Unauthorized – Požadavek neobsahuje platné přihlašovací údaje404 Not Found – Server nemůže najít požadovaný zdroj429 Too Many Requests – Klient odeslal příliš mnoho požadavků za daný čas5xx500 Internal Server Error – Server narazil na neočekávaný problém a nemůže odpovědět502 Bad Gateway – API server nemohl úspěšně kontaktovat jiný server potřebný k dokončení odpovědi504 Gateway Timeout – Server (fungující jako brána) neobdržel odpověď od upstream serveru včasimport 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}')
Úvod do API v Pythonu