API入門

Pythonを使ったAPI入門

Chris Ramakers

Engineering Manager

APIとは?

  • Application Programming Interface(アプリケーション・プログラミング・インターフェース)
  • 通信のための一連のルールや機能
  • ソフトウェアアプリケーション間のやり取りを可能にする

A diagram showing API interactions between an email client and an email server for sending an email to john@acme.com.

Pythonを使ったAPI入門

Web API、クライアント、サーバー

  • Web APIはHTTPを使ってインターネットを介して通信する
  • クライアントがサーバーにリクエストメッセージを送信
  • サーバーがクライアントにレスポンスメッセージを返す

A diagram showing client-server interaction over the internet via an API, with labeled request and response messages.

  • リクエスト/レスポンスのサイクル
Pythonを使ったAPI入門

Web APIの種類

  • SOAP
    • 厳格で形式的なAPI設計を重視
    • エンタープライズアプリケーション
  • REST
    • シンプルさとスケーラビリティを重視
    • 最も一般的なAPIアーキテクチャ
  • GraphQL
    • 柔軟性を重視
    • パフォーマンス向けに最適化
1 https://www.postman.com/state-of-api/api-technologies/#api-technologies
Pythonを使ったAPI入門

PythonでAPIを扱う

urllib

  • Pythonに標準で付属
  • 高機能だが、開発者にとってはあまり使いやすくない
from urllib.request import urlopen
api = "http://api.music-catalog.com/"

with urlopen(api) as response:
  data = response.read()
  string = data.decode()
  print(string)

リクエスト

  • 高機能だが、開発者にとってはあまり使いやすくない
  • 使いやすい
import requests
api = "http://api.music-catalog.com/"

response = requests.get(api)
print(response.text)
Pythonを使ったAPI入門

コードを書いてみましょう!

Pythonを使ったAPI入門

Preparing Video For Download...