Wprowadzenie do API w Pythonie
Chris Ramakers
Engineering Manager
4xxRozwiązanie: Poprawić żądanie
5xxRozwiązanie: Powinien naprawić administrator API
4xx401 Unauthorized - Żądanie nie zawiera prawidłowych danych uwierzytelniających404 Not Found - Serwer nie może znaleźć żądanego zasobu429 Too Many Requests - Klient wysłał zbyt wiele żądań w określonym czasie5xx500 Internal Server Error - Serwer napotkał nieoczekiwany problem uniemożliwiający odpowiedź502 Bad Gateway - Serwer API nie mógł skontaktować się z innym wymaganym serwerem504 Gateway Timeout - Serwer (działający jako brama) nie otrzymał odpowiedzi od serwera nadrzędnego w czasieimport 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}')
Wprowadzenie do API w Pythonie