Python API 入門
Chris Ramakers
Engineering Manager
4xx 用戶端錯誤解法:修正請求
5xx 伺服器錯誤解法:由 API 管理員修復
4xx 用戶端錯誤401 Unauthorized - 此請求缺少目標資源所需的有效驗證資訊404 Not Found - 伺服器找不到所請求的資源429 Too Many Requests - 用戶端在短時間內送出太多請求5xx 伺服器錯誤500 Internal Server Error - 伺服器發生非預期問題而無法回應502 Bad Gateway - API 伺服器無法成功連到完成回應所需的其他伺服器504 Gateway Timeout - 作為閘道的伺服器未及時收到上游伺服器回應import 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}')
Python API 入門