简体   繁体   中英

REST API - How to handle optional parameter in PUT method ? what is difference in implementation with PATCH method

I'm a little confused about put method with optional paramter.

suppose the mode is

Pet {
  name 
  catagory
  tag  (optional)
}

when I want to create a Pet, I can use post method, the tag can be omitted. when I want to update a Pet, the problem comes to me. According to the http spec, PUT method will update the entity by replaces the whole resource, which means I need to pass tag parameter. If I didn't pass tag , the default value will be empty, but it will cause the existing tag be override to empty.

For patch method, it will only update partial parameter no matter if it is optional. It's clear to understand.

I don't know if I misunderstand something, currently, in PUT method, I need to figure out what parameter is passed, and then update correspond field. But this seems the same with PATCH method.

An important thing to understand is that the HTTP specification describes the semantics (what do the different requests mean), but does not describe the implementation (how do you do it). That's deliberate - the specification basically says that your server should pretend to be a key/value store, but it doesn't restrict how you implement that.

PUT is roughly analogous to saving a file: "here is an array of bytes, save it using this key". In cases where your storage is a file system, then you just write the array of bytes to disk. If your storage is an in memory cache, then you just update your cached copy.

If your storage is some RDBMS database? Then you have some work to do, identifying which rows in your database need to be changed, and what commands need to be sent to the database to make that happen.

The point is that the client doesn't care -- as a server, you can change your underlying storage from RDBMS to document stores to files systems to whatever, and that's not any of the client's business.

in PUT method, I need to figure out what parameter is passed, and then update correspond field. But this seems the same with PATCH method.

Yes. In both cases, you need to figure out how to edit your resource in place.

PUT may feel a little bit easier, in that it is semantically equivalent to "delete the old version, then create a new version". You don't have to worry about merging the provided data to the state you already have stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM