RESTful way of getting a resource, but creating it if it doesn't exist yet

前端 未结 2 1299
南旧
南旧 2021-01-18 10:09

For a RESTful API that I\'m creating, I need to have some functionality that get\'s a resource, but if it doesn\'t exist, creates it and then returns it. I don\'t think this

相关标签:
2条回答
  • 2021-01-18 11:06

    very simple:

    1. Request: HEAD, examine response code: either 404 or 200. If you need the body, use GET.
    2. It not available, perform a PUT or POST, the server should respond with 204 and the Location header with the URL of the newly created resource.
    0 讨论(0)
  • 2021-01-18 11:07

    Does the client need to provide any information as part of the creation? If so then you really need to separate out GET and POSTas otherwise you need to send that information with each GET and that will be very ugly.

    If instead you are sending a GET without any additional information then there's no reason why the backend can't create the resource if it doesn't already exist prior to returning it. Depending on the amount of time it takes to create the resource you might want to think about going asynchronous and using 202 as per other answers, but that then means that your client has to handle (yet) another response code so it might be better off just waiting for the resource to be finalised and returned.

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