Request():patch()
PATCH リクエストを実行し、Response オブジェクトを返します。このメソッドは、サーバー上のリソースを部分的に更新するために使用します。
シグネチャ
patch(): Response
戻り値
Response - サーバーのレスポンスを含むレスポンスオブジェクト
説明
patch() メソッドは、Request オブジェクトの作成時に指定した URL に対して HTTP PATCH リクエストを送信します。PATCH リクエストは通常、既存のリソースに対して部分的な更新を行うために使用し、リクエストボディで指定されたフィールドのみを変更します。
patch() を呼び出す前に setParameter() を使用してリクエストボディにデータを追加します。
例
基本的な PATCH リクエスト
-- ユーザーの email フィールドのみ更新
local response = Request("https://api.example.com/users/123")
:setParameter("email", "newemail@example.com")
:patch()
JSON ヘッダー付き PATCH リクエスト
-- 複数フィールドで投稿を部分的に更新
local response = Request("https://api.example.com/posts/456")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer your-token-here")
:setParameter("title", "Updated Post Title")
:setParameter("status", "published")
:patch()
PATCH レスポンスの処理
-- ユーザープロフィールを更新してレスポンスを処理
local response = Request("https://api.example.com/users/789")
:setHeader("Content-Type", "application/json")
:setHeader("Authorization", "Bearer token123")
:setParameter("bio", "Updated bio information")
:setParameter("website", "https://mywebsite.com")
:patch()
local data = response:getData()
local statusCode = response:getResponseCode()
if statusCode == 200 then
print("ユーザーを更新しました!")
print("更新データ: " .. data)
elseif statusCode == 204 then
print("ユーザーを更新しました!(コンテンツなし)")
else
print("ユーザーの更新に失敗しました。ステータス: " .. statusCode)
end
条件付き PATCH 更新
-- リソースが変更されていない場合のみ更新
local response = Request("https://api.example.com/articles/123")
:setHeader("Content-Type", "application/json")
:setHeader("If-Match", "etag-value-here")
:setHeader("Authorization", "Bearer token")
:setParameter("content", "Updated article content")
:setParameter("lastModified", "2023-12-01")
:patch()
local status = response:getResponseCode()
if status == 412 then
print("更新に失敗しました: 別のユーザーがリソースを変更しています")
elseif status == 200 or status == 204 then
print("記事を更新しました")
end
フィールド選択付き PATCH
-- 他のフィールドは変更せずに特定のフィールドのみ更新
local response = Request("https://api.example.com/products/456")
:setHeader("Content-Type", "application/json")
:setParameter("price", "29.99")
:setParameter("stock", "150")
:setParameter("discount", "10")
:patch()
local updatedProduct = response:getData()
print("商品を更新しました: " .. updatedProduct)
注記
patch()を呼び出す前にsetParameter()を使用してリクエストボディにデータを追加します- PATCH リクエストには、リソース全体ではなく更新したいフィールドのみを含める必要があります
- PATCH と PUT の違いは、PATCH は部分的な更新を行うのに対し、PUT はリソース全体を置き換える点です
- 成功した PATCH 操作は通常、次のいずれかを返します:
200 OK— レスポンスボディに更新されたリソースを含む204 No Content— 更新は成功したがレスポンスボディが不要な場合
- このメソッドは Response オブジェクトを返し、レスポンスデータとステータスコードにアクセスできます
- リクエストが成功したかどうかを確認するため、常にレスポンスのステータスコードをチェックしてください
- PATCH リクエストは必ずしも冪等ではありません — 同じリクエストを複数回送信した場合の効果は実装によって異なります