0
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「requests」って何?

0
Posted at

Python「requests」って何?

requests は、Python で最もよく使われている
HTTP通信(WebサイトやAPIとのやりとり)を簡単に行うためのライブラリ。
難しいネットワーク処理を隠してくれるので、

Webページの取得
API(例:天気API、ChatGPT APIなど)の利用
データの送受信(GET/POST)
ファイルのアップロード
認証つきアクセス

などが、とてもシンプルに書ける。

基本の使い方

① GETリクエスト(データを取得)

import requests

response = requests.get("https://example.com")
print(response.status_code)   # ステータスコード
print(response.text)          # 取得したHTMLなどの内容

② POSTリクエスト(データを送信)

import requests

data = {"name": "Airi", "age": 20}
response = requests.post("https://example.com/api", json=data)

print(response.json())

json= を使うと自動で JSON に変換して送ってくれます。

③ ヘッダーをつける

APIキーをつけたりするときに使います。
ヘッダーは“手紙の封筒に書く情報”みたいなもの。
Webサーバーにアクセスするときに、

・自分は誰なのか
・どんな形式でデータを受け取りたいのか
・APIキー(鍵)を渡す
などの情報を送るために使う部分。
「この鍵を使ってアクセスさせてください」 と伝えているイメージ。

headers = {
    "Authorization": "Bearer xxxxx"
}

response = requests.get("https://api.example.com/data", headers=headers)

④ パラメータ付き(URLの ?key=value)

URL の “?○○=△△” の部分を自動で作ってくれる機能。
たとえば Google検索の URL ってこうなる

https://google.com/search?q=Tokyo&num=5

これを自動で作れるのが params=

params = {"q": "Tokyo", "limit": 5}
response = requests.get("https://example.com/search", params=params)

すると内部ではこうなる

https://example.com/search?q=Tokyo&limit=5

検索条件や設定を URL の後ろにくっつけるために使う。

⑤ JSONの取得

APIではほぼこれを使います。
API はほとんどの場合、JSON形式(中身が {} のやつ)でデータを返す。
こんなの↓

{
  "city": "Tokyo",
  "temperature": 12
}

response.json() を使うと、Python の辞書(dict)に変換してくれる。

data = response.json()
print(data["city"])  # "Tokyo"

APIからのデータを“Pythonでそのまま使える形”に変換する便利機能。

response = requests.get("https://example.com/data")
data = response.json()    # Pythonのdictに変換

print(data)

なぜ便利なの?

・標準ライブラリより 圧倒的に使いやすい
・Python界隈で デファクトスタンダード
・書くコード量が少なくて済む
・エラー処理も簡単

超ざっくりまとめ!

番号 内容 例えると?
1 GET ただアクセスする
2 POST データを送りながらアクセス
3 headers 身分証・APIキー
5 json() APIの返事をPythonで使いやすくする
0
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
0
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?