LoginSignup
213
108

More than 5 years have passed since last update.

PatchとPutの違いについて

Last updated at Posted at 2018-03-01

今までなんとなく使っていて、ちゃんと調べていなかったpatchメソッドとputメソッドの違いについて調べてみた。

調べる前はどっちもリソースを更新する時に使うものだよね?程度の認識。

Abstract

Several applications extending the Hypertext Transfer Protocol (HTTP)
require a feature to do partial resource modification. The existing
HTTP PUT method only allows a complete replacement of a document.
This proposal adds a new HTTP method, PATCH, to modify an existing
HTTP resource.

PATCH Method for HTTP

  • Putメソッドは更新というよりは置換
  • Patchメソッドは既存のリソースを更新・変更・修正

The HTTP method PUT means resource creation or replacement at some given URL.

Think files, for example. If you upload a file to S3 at some URL, you want either to create the file at that URL or replace an existing file if there’s one. That is PUT.

Edge Rails: PATCH is the new primary HTTP method for updates

PutはS3のあるURLにファイルをアップロードするイメージ。そのURLにファイルが無ければ新規でアップされるし、あれば置き換える。よく冪等というキーワードが出てくるが、何度やってもそのURLにはそのファイルがアップされている状態になる。こういう処理にPutを利用する。

Now let’s think about ordinary edit forms in typical Ruby on Rails applications. How many times are we sending a complete representation for replacement? Not always, perhaps we could say that it is even rare in practice that you do so. For example, the conventional created_at and updated_at timestamps normally can’t be set by end-users, though they are often considered to belong to the representation of resources that map to records.

中略

Because of that, the PATCH method was defined in 1995 and standarized later. PATCH is a method that is not safe, nor idempotent, and allows full and partial updates and side-effects on other resources.

Edge Rails: PATCH is the new primary HTTP method for updates

Railsでは、ユーザーが情報をまるごと置換えたと思ってもcreated_atupdated_atがあるし、Putのような処理になることは少ないから、"PATCH is the new primary HTTP method for updates"にしたよとのこと。

まとめ

  • Railsで開発している時に"更新"でイメージするような、リソースの一部を更新する処理はPatch
  • ファイルアップロードのような、指定したURLにあるリソースをまるごと置換えるような処理はPut
213
108
1

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
213
108