In a java REST API, using PATCH vs PUT to update an entity

后端 未结 1 816
你的背包
你的背包 2021-02-06 08:59

I am about to start development on a new rest api in Java. My question is about the use of PATCH - Why?

Lets say, we have an entity named Address.java

p         


        
相关标签:
1条回答
  • 2021-02-06 09:03

    Using PATCH to upload a modified version of an existing object is almost always problematic for exactly the reason you have outlined. If you want to use PATCH with JSON, I strongly suggest you follow either RFC 6902 or RFC 7396. I won't speak to 7396 because I'm not that familiar with it, but to follow 6902 you would define a separate resource for PATCH operations. In the example you gave, it would look like:

    PATCH http://localhost:8080/addresses/1
    [
        { "op": "replace", "path": "/line1", "value": "1234 NewAddressDownTheStreet ST" },
        { "op": "remove", "path": "/line2" }
    ]
    

    You would then process this, making a new entity object that started at the current server state and applied the changes in the PATCH. Run validation on the new entity object. If it passes, push it to the data layer. If it fails, return an error code.

    If PUT doesn't add too much overhead, it is a good idea. Idempotency is a nice thing to have. The tradeoff is that you're pushing more data over the wire. If your resource is not large and not accessed often, that's maybe not such a big deal. If your resource is large and is accessed often, that can start to add significant overhead. Of course, we can't tell you the tipping point.

    You also seem to have completely tied your resource model to your database model. Good database table design and good resource design often look very different for non-trivial projects. I understand that many frameworks drive you in that direction, but you if you haven't seriously considered decoupling them, you might want to.

    0 讨论(0)
提交回复
热议问题