Consequences of POST not being idempotent (RESTful API)

前端 未结 6 1474
傲寒
傲寒 2021-01-30 09:13

I am wondering if my current approach makes sense or if there is a better way to do it.

I have multiple situations where i want to create new objects and let the server

6条回答
  •  隐瞒了意图╮
    2021-01-30 09:53

    well it all depends, to start with you should talk more about URIs, resources and representations and not be concerned about objects.

    The POST Method is designed for non-idempotent requests, or requests with side affects, but it can be used for idempotent requests.

    on POST of form data to /some_collection/

    normalize the natural key of your data (Eg. "lowercase" the Title field for a blog post)
    calculate a suitable hash value (Eg. simplest case is your normalized field value)
    lookup resource by hash value
    if none then
        generate a server identity, create resource
            Respond =>  "201 Created", "Location": "/some_collection/" 
    if found but no updates should be carried out due to app logic
            Respond => 302 Found/Moved Temporarily or 303 See Other 
            (client will need to GET that resource which might include fields required for updates, like version_numbers)
    if found but updates may occur
       Respond => 307 Moved Temporarily, Location: /some_collection/ 
       (like a 302, but the client should use original http method and might do automatically) 
    

    A suitable hash function might be as simple as some concatenated fields, or for large fields or values a truncated md5 function could be used. See [hash function] for more details2.

    I've assumed you:

    • need a different identity value than a hash value
    • data fields used for identity can't be changed

提交回复
热议问题