<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>「raise_for_status」タグの記事一覧Python Tech</title>
	<atom:link href="https://tech.nkhn37.net/tag/raise_for_status/feed/" rel="self" type="application/rss+xml" />
	<link>https://tech.nkhn37.net</link>
	<description>Python学習サイト</description>
	<lastBuildDate>Sun, 11 Jan 2026 03:23:46 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>

<image>
	<url>https://tech.nkhn37.net/wp-content/uploads/2021/01/cropped-lion-normal-clear-1-32x32.png</url>
	<title>「raise_for_status」タグの記事一覧Python Tech</title>
	<link>https://tech.nkhn37.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>【Python】requestsの基本的な使い方</title>
		<link>https://tech.nkhn37.net/python-requests-basic/</link>
					<comments>https://tech.nkhn37.net/python-requests-basic/#respond</comments>
		
		<dc:creator><![CDATA[naoki-hn]]></dc:creator>
		<pubDate>Thu, 04 Jan 2024 20:00:00 +0000</pubDate>
				<category><![CDATA[requests]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[delete]]></category>
		<category><![CDATA[get]]></category>
		<category><![CDATA[httperror]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[param]]></category>
		<category><![CDATA[post]]></category>
		<category><![CDATA[put]]></category>
		<category><![CDATA[raise_for_status]]></category>
		<category><![CDATA[timeout]]></category>
		<guid isPermaLink="false">https://tech.nkhn37.net/?p=10046</guid>

					<description><![CDATA[Python における HTTP 接続のためのライブラリである requests の基本的な使い方を解説します。 requests モジュール requests は、HTTP 接続に関する機能を提供するサードパーティ製の [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Python における HTTP 接続のためのライブラリである <span class="jinr-d--text-color d--marker1 d--bold"><code>requests</code></span> の基本的な使い方を解説します。</p>



<h2 class="wp-block-heading jinr-heading d--bold"><code>requests</code> モジュール</h2>



<p class="wp-block-paragraph"><span class="jinr-d--text-color d--marker1 d--bold"><code>requests</code></span> は、HTTP 接続に関する機能を提供するサードパーティ製の Python ライブラリです。<code>requests</code> は、インターネット上のデータを扱うための機能を多く備えており、HTTP 接続を簡単に行うことができます。</p>



<p class="wp-block-paragraph">Python の標準ライブラリとしては、<code>urllib</code> が存在しますが、<code>requests</code> の方が使いやすく直感的な API を使用していることから <code>requests</code> の方が広く使用されており、デファクトスタンダードとみなされています。</p>



<p class="wp-block-paragraph">この記事では、HTTP リクエストを作成して通信する簡単な例を使用して <span class="jinr-d--text-color d--marker1 d--bold"><code>requests</code> の基本的な使い方</span>を紹介します。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph"><code>urllib</code> は Python 標準ライブラリであるため外部ライブラリに依存したくない場合に有用です。<code>urllib</code> の使い方は「<a href="https://tech.nkhn37.net/python-urllib-basic/" target="_blank" rel="noreferrer noopener">urllibの基本的な使い方</a>」を参考にしてください。</p>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold">HTTP リクエスト</h3>



<p class="wp-block-paragraph">Web システムで、サーバーとクライアントがやり取りするには、クライアントがサーバーに対して特定の操作を行うための HTTP リクエストを送信します。HTTP リクエストには、いくつかのメソッドがあり、代表的なものは以下です。</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>メソッド</th><th>概要</th></tr></thead><tbody><tr><td><code>GET</code></td><td>リソースの取得をサーバーに要求します。データ取得するための最も一般的に使用されるメソッドで、URL にクエリパラメータを含めてリクエストを送信し、サーバーからの応答を受け取ります。</td></tr><tr><td><code>POST</code></td><td>新しいリソースを作成するためにサーバーにデータを送信します。例えば、フォーム送信や DB へのデータ追加に使用します。<code>POST</code> は、データを HTTP リクエストのボディに含めて送信します。</td></tr><tr><td><code>PUT</code></td><td>指定されたリソースを更新するために使用します。<code>PUT</code> は、既存のリソースを置き換えるために使用され、HTTP リクエストのボディに更新データを含めて送信します。</td></tr><tr><td><code>DELETE</code></td><td>指定されたリソースをサーバーから削除するために使用します。</td></tr></tbody></table></figure>



<p class="wp-block-paragraph">他にも HTTP リクエストで使用できるメソッドはありますが、上記が最も代表的なものです。<code>GET</code> はデータ取得、<code>POST</code> はデータ登録、<code>PUT</code> はデータ更新、<code>DELETE</code>はデータ削除といった操作に使用されます。</p>



<h3 class="wp-block-heading jinr-heading d--bold">テスト用サービス httpbin.org</h3>



<h4 class="wp-block-heading jinr-heading d--bold">HTTP リクエストとレスポンスをテストする</h4>



<p class="wp-block-paragraph">HTTP リクエストとレスポンスのテストをするためには、API を提供するサーバーが必要になります。今回は「<a href="https://httpbin.org/" target="_blank" rel="noreferrer noopener">httpbin.org</a>」を使用します。</p>



<p class="wp-block-paragraph">httpbin.org は、HTTP リクエストとレスポンスのテストに使用される人気のオンラインサービスで、開発者が HTTP リクエストを送信し、そのレスポンスを確認できるように設計されています。</p>



<p class="wp-block-paragraph">様々な種類の HTTP リクエストをシミュレートしてレスポンスデータを分析することで、Web 開発者は自分のコードが予期したとおりに動作するかをテストすることが可能です。httpbin.org は、WebAPI の開発や HTTP クライアントのライブラリ、フレームワークのテストなどに広く使用されています。</p>



<h4 class="wp-block-heading jinr-heading d--bold">Docker 環境の利用</h4>



<p class="wp-block-paragraph">httpbin.org は、通信したタイミングによってサービスが不安定であることがあります。httpbin.org のサービスは、Docker 環境が用意されているため、Docker 環境が手元にある場合には、以下のコマンドでローカル実行してテストする方が安定的に動作確認ができます。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">docker run --rm -p 8080:80 kennethreitz/httpbin</pre>



<p class="wp-block-paragraph">上記コマンドを実行すると「<code>kennethreitz/httpbin</code>」というコンテナ環境をインストールして起動します。<code>--rm</code> オプションは、サービスを切ったタイミングでコンテナを削除するコマンドで、<code>-p 8080:80</code> はポートの接続設定であり、ローカル環境からは <code>8080</code> ポートを使用してコンテナのサービスにアクセスできます。</p>



<p class="wp-block-paragraph">なお、httpbin.org にアクセスする場合は、https で SSL 通信ができますが、ローカルの Docker 環境では SSL 通信は対応していないので http でアクセスする必要があります</p>



<p class="wp-block-paragraph">以降のプログラム例では Docker 環境への接続を使用していますが、httpbin.org への URL もコメントアウトしているため、httpbin.org へ直接つないで試す場合は、コメントアウトを切り替えて試してみてください。</p>



<section class="wp-block-jinr-blocks-iconbox b--jinr-block b--jinr-iconbox"><div class="d--simple-iconbox6 ">
			<i class="jif jin-ifont-v2books" aria-hidden="true"></i>
			<div class="a--jinr-iconbox">
<p class="wp-block-paragraph">Docker インストールや使い方は以下を参考にしてください。</p>



<ul class="wp-block-list jinr-list">
<li><a href="https://tech.nkhn37.net/docker-desktop-for-windows-install/" target="_blank" rel="noreferrer noopener">Docker Desktop for Windowsのインストール方法</a></li>



<li><a href="https://tech.nkhn37.net/docker-container-python/" target="_blank" rel="noreferrer noopener">Dockerイメージを取得してコンテナを作成・動作させる方法</a></li>
</ul>
</div>
		</div></section>



<h3 class="wp-block-heading jinr-heading d--bold"><code>requests</code> の基本的な使い方</h3>



<p class="wp-block-paragraph"><code>requests</code> を使用して基本的な <code>GET</code> / <code>POST</code> / <code>PUT</code> / <code>DELETE</code> の HTTP リクエストを作成し、サーバーとやり取りする方法を紹介します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">リソースの取得をサーバーに要求する <code>get</code></h4>



<h5 class="wp-block-heading jinr-heading d--bold">データを取得する</h5>



<p class="wp-block-paragraph">サーバーからリソースの取得をするには、<code>GET</code> メソッドの HTTP リクエストを送信します。<code>requests</code> モジュールでは、<code>GET</code> に該当する <span class="jinr-d--text-color d--marker1 d--bold"><code>get</code></span> 関数が用意されています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/get"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/get"

# データ取得リクエスト
r = requests.get(url)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">[status_code]:
200 OK

[headers]:
{'Server': 'gunicorn/19.9.0', 'Date': 'Wed, 17 Dec 2025 21:08:38 GMT', 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Content-Length': '274', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true'}

[content]:
b'{\n  "args": {}, \n  "headers": {\n    "Accept": "*/*", \n    "Accept-Encoding": "gzip, deflate", \n    "Connection": "keep-alive", \n    "Host": "localhost:8080", \n    "User-Agent": "python-requests/2.32.5"\n  }, \n  "origin": "xxx.xxx.xxx.xxx", \n  "url": "http://localhost:8080/get"\n}\n'

[text]:
{
  "args": {}, 
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "origin": "xxx.xxx.xxx.xxx",
  "url": "http://localhost:8080/get"
}

[json]:
{'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive', 'Host': 'localhost:8080', 'User-Agent': 'python-requests/2.32.5'}, 'origin': 'xxx.xxx.xxx.xxx', 'url': 'http://localhost:8080/get'}</pre>



<p class="wp-block-paragraph"><code>get</code> 関数には、データを取得するための URL を指定します。</p>



<p class="wp-block-paragraph">今回は「<code>http://localhost:8080/get</code>」として Docker のローカル環境を指定しています。直接 httpbin へアクセスする場合は「<code>http://httpbin.org/get</code>」の方のコメントアウトを外して、Docker の方をコメントアウトして切り替えて試してください。（以降の例も同様です。）</p>



<p class="wp-block-paragraph">HTTP 通信では、通信結果をステータスコードで確認できます。ステータスコードは <code>status_code</code>、内容は <code>reason</code> プロパティにより確認できます。サーバーからの応答のヘッダーは <code>headers</code> プロパティ、生データは <code>content</code> プロパティで取得できます。</p>



<p class="wp-block-paragraph"><code>content</code> は生のバイナリデータとなっていますが、応答の文字列を取得するための <code>text</code> プロパティが用意されているため簡単に文字列として取り出せます。また、JSON 形式として取得したい場合は、<code>json</code> メソッドを使用します。</p>



<p class="wp-block-paragraph">なお、応答が JSON でない場合には、<code>r.json()</code> の部分で <code>requests.exceptions.JSONDecodeError</code> が発生するため例外処理をするか、事前に <code>r.headers.get("Content-Type", "")</code> に <code>application/json</code> が含まれるかをチェックするなどしてください。httpbin は JSON が返ってくることが分かっているため、例では簡単のため処理を省略します。</p>



<h5 class="wp-block-heading jinr-heading d--bold">クエリパラメータを含めてリクエストを送信する</h5>



<p class="wp-block-paragraph"><code>GET</code> リクエスト時にサーバーに対して条件を指定する際には、クエリパラメータを使用します。クエリパラメータを指定するには、<code>get</code> 関数の <span class="jinr-d--text-color d--marker1 d--bold"><code>params</code></span> 引数で指定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/get"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/get"

# クエリパラメータを定義
params = {"key1": "value1", "key2": "value2"}

# データ取得リクエスト (クエリパラメータ付き)
r = requests.get(url, params=params)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】(text部分のみ表示)
[text]:
{
  "args": {
    "key1": "value1",
    "key2": "value2"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "origin": "xxx.xxx.xxx.xxx",
  "url": "http://localhost:8080/get?key1=value1&amp;key2=value2"
}</pre>



<p class="wp-block-paragraph">クエリパラメータを含めてリクエストを送信するには、クエリパラメータを辞書で用意します。例では、<code>"key1"</code> と <code>"key2"</code> がクエリのキーであり、<code>"value1"</code> と <code>"value2"</code> が対応する値となります。</p>



<h4 class="wp-block-heading jinr-heading d--bold">新しいリソースを作成する <code>post</code></h4>



<p class="wp-block-paragraph">サーバーに新しいリソースを作成するには、<code>POST</code> メソッドの HTTP リクエストを送信します。<code>requests</code> モジュールでは、<code>POST</code>に該当する <span class="jinr-d--text-color d--marker1 d--bold"><code>post</code></span> 関数が用意されています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/post"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/post"

# 登録データの作成
payload = {"name": "Taro", "age": 30}

# データ登録リクエスト (json引数)
r = requests.post(url, json=payload)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】(text部分のみ表示)
[text]:
{
  "args": {},
  "data": "{\"name\": \"Taro\", \"age\": 30}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Content-Length": "27",
    "Content-Type": "application/json",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "json": {
    "age": 30,
    "name": "Taro"
  },
  "origin": "xxx.xxx.xxx.xxx",
  "url": "http://localhost:8080/post"
}</pre>



<p class="wp-block-paragraph">登録するデータは、辞書で作成します。リクエスト時には、<code>json</code> 引数で当該データを指定することで登録データをサーバーへ送信します。なお、URL としては、<code>POST</code> リクエストのエンドポイントとして「<code>http://localhost:8080/post</code>」を指定します。</p>



<p class="wp-block-paragraph">近年のウェブアプリケーションや API では JSON 形式でのデータのやり取りが一般的です。そのため、<code>requests</code> ライブラリでは、<code>json</code> 引数が使用されることが多いです。</p>



<p class="wp-block-paragraph">ただし、HTML フォームからのデータ送信に使用される <code>application/x-www-form-urlencoded</code> 形式としてデータを送信したい場合は、<code>data</code> 引数を使用します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/post"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/post"

# 登録データの作成
payload = {"name": "Taro", "age": 30}

# データ登録リクエスト (data引数)
r = requests.post(url, data=payload)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】(text部分のみ表示)
[text]:
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "age": "30",
    "name": "Taro"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Content-Length": "16",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "json": null,
  "origin": "xxx.xxx.xxx.xxx",
  "url": "http://localhost:8080/post"
}</pre>



<p class="wp-block-paragraph">サーバー側の実装によってどちらの形式も受け入れることがありますが、API のドキュメントで指定された形式に従うのがベストプラクティスです。API のドキュメントを確認し、適切なデータ形式でリクエストを行うようにしましょう。</p>



<p class="wp-block-paragraph">以降の <code>PUT</code>、<code>DELETE</code> の例では <code>json</code> 引数を使用しますが、<code>data</code> 引数も使用可能です。</p>



<h4 class="wp-block-heading jinr-heading d--bold">指定されたリソースを更新する <code>put</code></h4>



<p class="wp-block-paragraph">指定されたリソースを更新するには、<code>PUT</code> メソッドの HTTP リクエストを送信します。<code>requests</code> モジュールでは、<code>PUT</code> に該当する <span class="jinr-d--text-color d--marker1 d--bold"><code>put</code></span> 関数が用意されています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/put"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/put"

# 更新データの作成
payload = {"name": "Miki", "age": 25}

# データ更新リクエスト
r = requests.put(url, json=payload)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】(text部分のみ表示)
[text]:
{
  "args": {},
  "data": "{\"name\": \"Miki\", \"age\": 25}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Content-Length": "27",
    "Content-Type": "application/json",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "json": {
    "age": 25,
    "name": "Miki"
  },
  "origin": "xxx.xxx.xxxx.xxx",
  "url": "http://localhost:8080/put"
}</pre>



<p class="wp-block-paragraph">更新したいデータは、辞書で作成します。リクエスト時には、<code>json</code> 引数で当該データを指定することで更新データをサーバーへ送信します。なお、URL としては、<code>PUT</code> リクエストのエンドポイントとして「<code>http://localhost:8080/put</code>」を指定します。</p>



<h4 class="wp-block-heading jinr-heading d--bold">指定されたリソースをサーバーから削除する <code>delete</code></h4>



<p class="wp-block-paragraph">指定されたリソースをサーバーから削除するには、<code>DELETE</code> メソッドの HTTP リクエストを送信します。<code>requests</code> モジュールでは、<code>DELETE</code> に該当する <span class="jinr-d--text-color d--marker1 d--bold"><code>delete</code></span> 関数が用意されています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/delete"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/delete"

# 削除データの指定
payload = {"id": 123}

# データ削除リクエスト
r = requests.delete(url, json=payload)

# ステータスコード
print(f"[status_code]:\n{r.status_code} {r.reason}\n")
# ヘッダー
print(f"[headers]:\n{r.headers}\n")
# 応答の生データ(バイナリ)
print(f"[content]:\n{r.content}\n")
# 応答の文字列形式
print(f"[text]:\n{r.text}\n")
# 応答のJSON形式
print(f"[json]:\n{r.json()}\n")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】(text部分のみ表示)
[text]:
{
  "args": {},
  "data": "{\"id\": 123}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "keep-alive",
    "Content-Length": "11",
    "Content-Type": "application/json",
    "Host": "localhost:8080",
    "User-Agent": "python-requests/2.32.5"
  },
  "json": {
    "id": 123
  },
  "origin": "xxx.xxx.xxx.xxx",
  "url": "http://localhost:8080/delete"
}</pre>



<p class="wp-block-paragraph">例では、<code>DELETE</code> リクエストのエンドポイントで「<code>http://localhost:8080/delete</code>」を指定し、削除データは <code>json</code> 引数で対象の <code>id</code> を指定しています。</p>



<p class="wp-block-paragraph">ただし、URL パスとして削除対象を指定する API や、<code>DELETE</code> でボディを受け付けないサーバーもありえます。API の仕様をよく確認して使用してください。</p>



<h4 class="wp-block-heading jinr-heading d--bold">汎用的にリクエストを送信する <code>request</code></h4>



<p class="wp-block-paragraph">上記の例では、<code>GET</code> / <code>POST</code> / <code>PUT</code> / <code>DELETE</code> それぞれに対応する関数を使用してきましたが、より汎用的な関数として <code>request</code> 関数があります。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests

# ===== URLを指定 (GET)
# url = "http://httpbin.org/get"
url = "http://localhost:8080/get"

# データ取得リクエスト
r = requests.request("GET", url)
# ステータスコード
print(f"[GET] {r.status_code} {r.reason}")

# ===== URLを指定 (POST)
# url = "http://httpbin.org/post"
url = "http://localhost:8080/post"

# 登録データの作成
payload = {"name": "Taro", "age": 30}
# データ登録リクエスト
r = requests.request("POST", url, json=payload)
# ステータスコード
print(f"[POST] {r.status_code} {r.reason}")

# ===== URLを指定 (PUT)
# url = "http://httpbin.org/put"
url = "http://localhost:8080/put"

# 更新データの作成
payload = {"name": "Miki", "age": 25}
# データ更新リクエスト
r = requests.request("PUT", url, json=payload)
# ステータスコード
print(f"[PUT] {r.status_code} {r.reason}")

# ===== URLを指定 (DELETE)
# url = "http://httpbin.org/delete"
url = "http://localhost:8080/delete"

# 削除データの指定
payload = {"id": 123}
# データ削除リクエスト
r = requests.request("DELETE", url, json=payload)
# ステータスコード
print(f"[DELETE] {r.status_code} {r.reason}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
[GET] 200 OK
[POST] 200 OK
[PUT] 200 OK
[DELETE] 200 OK</pre>



<p class="wp-block-paragraph"><code>request</code> 関数には、<code>"GET"</code> などの HTTP メソッドを文字列で指定し、その後で <code>url</code> や <code>params</code> などを指定します。<code>get</code> 関数などの個別の関数は、内部では以下のように <code>request</code> 関数を呼び出しています。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def get(url, params=None, **kwargs):
    r"""Sends a GET request.

    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response &lt;Response>` object
    :rtype: requests.Response
    """

    return request("get", url, params=params, **kwargs)</pre>



<p class="wp-block-paragraph">例では、ステータスコードのみ表示していますが、各種情報へのアクセス方法はこれまで紹介した方法と同様です。</p>



<p class="wp-block-paragraph">個別の関数と <code>request</code> 関数のどちらを使うべきかというところに悩むかもしれませんが、可読性を考慮するのであれば <code>get</code> 関数などの個別の関数を呼び出す方がよいと思います。一方で、汎用的な HTTP アクセス用のクラスを作る場合などでは、<code>request</code> 関数を使うことがおすすめです。</p>



<h4 class="wp-block-heading jinr-heading d--bold">エラーステータスコードの場合に例外を発生させる</h4>



<p class="wp-block-paragraph">Web サービスでは、サーバーからの応答がエラーステータスコード（通常 400 以上)となる場合があります。そのような場合のために、例外処理の実装が重要です。</p>



<p class="wp-block-paragraph">リクエストの際にエラーステータスコードの場合に例外を発生させるには、<span class="jinr-d--text-color d--marker1 d--bold"><code>raise_for_status</code></span> を使用します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests
from requests.exceptions import HTTPError, RequestException

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/status/400"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/status/400"

try:
    # URLからデータを取得する
    r = requests.get(url)
    # HTTPエラーが発生した場合、例外を発生させる
    r.raise_for_status()

    # 応答結果の表示
    print(f"text:\n {r.text}")

except HTTPError as e:
    print(f"HTTPエラー: {e}")
except RequestException as e:
    print(f"通信エラー: {e}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
HTTPエラー: 400 Client Error: BAD REQUEST for url: http://localhost:8080/status/400</pre>



<p class="wp-block-paragraph">httpbin.org では、特定のステータスコードのエンドポイントが用意されています。例では 400 番の応答が返ってくる接続先にリクエストを送信しています。</p>



<p class="wp-block-paragraph"><code>raise_for_status</code> は、<code>4xx</code> や <code>5xx</code> のエラーステータスコードの場合に <span class="jinr-d--text-color d--marker1 d--bold"><code>HTTPError</code></span> の例外を発生させます。例外は <code>except</code> でキャッチして処理します。</p>



<p class="wp-block-paragraph">なお、例外クラスは他にもありますが <code>RequestException</code> は <code>requests</code> が送出する例外の基底クラスであるため、最後にその他の通信の例外をまとめて捕捉しています。 </p>



<h4 class="wp-block-heading jinr-heading d--bold">タイムアウトを設定する</h4>



<p class="wp-block-paragraph">Web サービスでは、リクエストが大量にくると処理が遅くなる場合があります。このような場合のために、タイムアウトを設定して一定時間を経過してもレスポンスがない場合は、タイムアウトとして処理をします。</p>



<p class="wp-block-paragraph">タイムアウトの指定は、<span class="jinr-d--text-color d--marker1 d--bold"><code>timeout</code></span> 引数で設定します。</p>



<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import requests
from requests.exceptions import Timeout, RequestException

# httpbin へアクセスする場合は以下を有効化
# url = "https://httpbin.org/get"

# Docker 環境で実行する場合は以下を有効化
url = "http://localhost:8080/get"

try:
    # URLからデータを取得する
    # タプルで指定する場合は (接続タイムアウト, 読み取りタイムアウト)を指定
    # timeout=5.0 のようにすると、接続・読み取りともに5秒のタイムアウト設定となる
    r = requests.get(url, timeout=(3.0, 5.0))

    # 応答結果の表示
    print(f"text:\n {r.text}")

except Timeout as e:
    print(f"タイムアウトエラー: {e}")
except RequestException as e:
    print(f"通信エラー: {e}")</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="false" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">【実行結果】
タイムアウトエラー: HTTPConnectionPool(host='localhost', port=8080): Read timed out. (read timeout=1e-06)</pre>



<p class="wp-block-paragraph">タイムアウトが発生した場合は、<span class="jinr-d--text-color d--marker1 d--bold"><code>Timeout</code></span> の例外が発生します。<code>timeout</code> はタプルで <code>(接続タイムアウト, 読み取りタイムアウト)</code> という形式で秒単位で指定できます。また、「<code>timeout=5.0</code>」のように指定すると、接続・読み取りともに同じ値でのタイムアウト設定となります。</p>



<p class="wp-block-paragraph">例では、タイムアウト設定を非常に小さな値にしてみるとタイムアウトの発生を確認できます。なお、Docker 環境の場合はローカル環境で非常に応答が速いため、非常に小さい値に設定しないとタイムアウトエラーが発生しない場合があります。</p>



<h2 class="wp-block-heading jinr-heading d--bold"><code>requests</code> の利用例</h2>



<p class="wp-block-paragraph"><code>requests</code> モジュールを使用すると公開されている便利な API を使うこともできて非常に便利です。利用例を紹介します。</p>



<h3 class="wp-block-heading jinr-heading d--bold">OpenWeather の API</h3>



<p class="wp-block-paragraph"><a href="https://openweathermap.org/" target="_blank" rel="noreferrer noopener">OpenWeather</a> は、グローバルな気象データサービスを提供する会社です。OpenWeather サービスは、世界中の天気予報、歴史的気象データ、気象条件のリアルタイムデータ、衛星画像、気象アラート および その他の気象関連情報を提供します。</p>



<p class="wp-block-paragraph"><code>requests</code> モジュールを使って OpenWeather の API を使う方法については「<a href="https://tech.nkhn37.net/python-openweather-api/" target="_blank" rel="noreferrer noopener">OpenWeatherのAPI使用方法</a>」で紹介しているので参考にしてください。</p>



<h2 class="wp-block-heading jinr-heading d--bold">まとめ</h2>



<p class="wp-block-paragraph">Python における HTTP 接続のためのライブラリである <span class="jinr-d--text-color d--marker1 d--bold"><code>requests</code></span> の基本的な使い方を解説しました。</p>



<p class="wp-block-paragraph"><code>requests</code> を使用して基本的な <code>GET</code> / <code>POST</code> / <code>PUT</code> / <code>DELETE</code> メソッドの HTTP リクエストを作成しサーバーとやり取りする方法を例を使って紹介しました。また、HTTP エラーやタイムアウトに関する例外処理の方法についても説明しています。</p>



<p class="wp-block-paragraph">Web 開発において HTTP リクエストとレスポンスの扱いについては基本的なものです。使い方の基本をしっかり理解してもらえたらと思います。</p>



<section class="wp-block-jinr-blocks-simplebox b--jinr-block-container"><div class="b--jinr-block b--jinr-box d--heading-box8  "><div class="a--simple-box-title d--bold">ソースコード</div><div class="c--simple-box-inner">
<p class="wp-block-paragraph">上記で紹介しているソースコードについては <a href="https://github.com/nkhn37/python-tech-sample-source/tree/main/python-libraries/requests" target="_blank" rel="noreferrer noopener">GitHub</a> にて公開しています。参考にしていただければと思います。</p>
</div></div></section>


<section class="b--jinr-block b--jinr-blogcard d--blogcard-hover-up d--blogcard-style1 d--blogcard-mysite t--round "><div class="a--blogcard-label ef">あわせて読みたい</div><a class="o--blogcard-link t--round" href="https://tech.nkhn37.net/python-tech-summary-page/"><div class="c--blogcard-image"><img decoding="async" class="a--blogcard-img-src" width="128" height="72" src="https://tech.nkhn37.net/wp-content/uploads/2024/08/Python-Tech-Pythonプログラミングガイド_new1-640x360.jpg" alt="【Python Tech】プログラミングガイド" /></div><div class="a--blogcard-title d--bold">【Python Tech】プログラミングガイド</div></a></section>


<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://tech.nkhn37.net/python-requests-basic/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Disk: Enhanced  を使用したページ キャッシュ

Served from: tech.nkhn37.net @ 2026-06-11 16:01:10 by W3 Total Cache
-->