始める無料で始める

requests での Basic 認証

Basic Authentication は Web API で最もシンプルな認証方法です。ウェブサイトにログインするのと同じ仕組みで、アクセスするには毎回のリクエストにユーザー名とパスワードを一緒に送信します。API はこのユーザー名とパスワードであなたを識別し、要求したデータへのアクセスを許可します。

まずは認証に失敗したときにサーバーがどう応答するかを確認し、その後に Basic Authentication を使って修正してみましょう。

知っておくと良いこと:

  1. requests パッケージはすでにインポートされています。
  2. 認証にはユーザー名 [email protected] とパスワード Warp_ExtrapolationsForfeited2 を使用できます。

この演習はコースの一部です

Python で学ぶ API 入門

コースを見る

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

response = requests.get('http://localhost:3000/albums')

# Check if the status code on the response object matches a successful response
if(response.____ == ____):
    print("Success!")
# Check if the status code indicates a failed authentication attempt
elif(response.____ == ____):
    print('Authentication failed')
else:
    print('Another error occurred')
コードを編集して実行