1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python入門 第17章】API連携ツールを作ろう🔗Webサービスとデータのやりとりを自動化🐍✨

Last updated at Posted at 2025-08-16

【Python入門 第17章】API連携ツールを作ろう🔗Webサービスとデータのやりとりを自動化🐍✨

こんにちは、 PythonTimesの蛇ノ目いろは です🌿
今回は「API連携ツールの作り方」について解説するよ!


🌐 APIってなに?

API(Application Programming Interface) とは、
アプリとアプリをつなぐ「データのやりとりの窓口」のこと。

PythonからAPIを使えば、

  • 天気情報の取得
  • チャットサービスとの連携
  • データベースやGoogleサービスとの接続
    …などができちゃう✨

🧰 使用ライブラリ:requests

pip install requests

requests はWeb上のAPIと簡単につながる、定番の通信ライブラリだよ!


🔍 GETリクエストの基本(天気API風の例)

import requests

url = "https://api.example.com/weather"
params = {"city": "Tokyo"}

response = requests.get(url, params=params)

if response.status_code == 200:
    data = response.json()
    print("気温:", data["temperature"])
else:
    print("エラー発生:", response.status_code)
  • params でクエリ文字列を指定
  • .json() でレスポンスを辞書型に変換できる!

✏️ POSTリクエストの基本(データ送信)

url = "https://api.example.com/contact"
payload = {"name": "いろは", "message": "こんにちは!"}

response = requests.post(url, json=payload)

print("ステータスコード:", response.status_code)
  • json= に辞書を渡すと自動でJSON変換してくれる!

🔐 APIキーが必要な場合

headers = {
    "Authorization": "Bearer sk-あなたのAPIキー"
}

response = requests.get(url, headers=headers)

セキュリティのため、 APIキーは環境変数や .envファイル に保存してね!


✅ PEP8的な設計ポイント

  • 定数は大文字で定義しよう(例: API_URL = "https://..."
  • 関数で処理を分けるとテストしやすい!
def get_weather(city):
    ...

📌 まとめ

  • APIを使えば、 外部サービスとデータのやりとり が簡単に!
  • requests.get() post() で接続&送受信
  • レスポンスは .json() で辞書化して扱いやすく✨
  • 設計もPEP8に沿って、安全でスッキリ書こう🐍

次回は、
「第18章:PDF / Word / PowerPoint 操作」 をお届け予定📄
Pythonでオフィス文書を自由自在にいじってみよう!

フォローしてくれたらうれしいな🐍🔗

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?