API認証

Pythonを使ったAPI入門

Chris Ramakers

Engineering Manager

機微データへのアクセス

A user trying to access music albums via a client. The request is sent over the Internet to a server through an API but receives a "401 Unauthorized" response.

Pythonを使ったAPI入門

機微データへのアクセス

A user accessing music albums via a client, providing a username and password. The request is sent over the Internet to a server through an API and receives a "200 OK" response, indicating successful access.

Pythonを使ったAPI入門

認証方式

認証方式 実装のしやすさ セキュリティ評価
Basic 認証 ⭐ ⭐ ⭐ ⭐ ⭐ ⭐ ☆ ☆ ☆ ☆
APIキー/トークン認証 ⭐ ⭐ ⭐ ⭐ ☆ ⭐ ⭐ ☆ ☆ ☆
JWT認証 ⭐ ⭐ ⭐ ☆ ☆ ⭐ ⭐ ⭐ ⭐ ☆
OAuth 2.0 ⭐ ⭐ ☆ ☆ ☆ ⭐ ⭐ ⭐ ⭐ ⭐

ヒント: 使用しているAPIのドキュメントを参照して、どの認証方式を使うべきか確認しましょう!

Pythonを使ったAPI入門

Basic認証

requestsパッケージでのBasic認証

# This will automatically add a Basic Authentication header before sending the request
requests.get('http://api.music-catalog.com', auth=('username', 'password'))
Pythonを使ったAPI入門

APIキー/トークン認証

クエリパラメータを使う

http://api.music-catalog.com/albums?access_token=faaa1c97bd3f4bd9b024c708c979feca
params = {'access_token': 'faaa1c97bd3f4bd9b024c708c979feca'}
requests.get('http://api.music-catalog.com/albums', params=params)

Authorizationヘッダーで「Bearer」を使う

headers = {'Authorization': 'Bearer faaa1c97bd3f4bd9b024c708c979feca'}
requests.get('http://api.music-catalog.com/albums', headers=headers)
Pythonを使ったAPI入門

練習しましょう!

Pythonを使ったAPI入門

Preparing Video For Download...