获取资源的 RESTful 方式,但如果尚不存在则创建它 [英] RESTful way of getting a resource, but creating it if it doesn't exist yet

查看:21
本文介绍了获取资源的 RESTful 方式,但如果尚不存在则创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我正在创建的 RESTful API,我需要有一些获取资源的功能,但如果它不存在,则创建它然后返回它.我不认为这应该是 GET 请求的默认行为.我可以在给 GET 请求的某个参数上启用此功能,但这似乎有点脏.

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 should be the default behaviour of a GET request. I could enable this functionality on a certain parameter I give to the GET request, but it seems a little bit dirty.

主要的一点是我只想为此做一个请求,因为这些请求将通过可能具有较慢互联网连接的移动设备完成,所以我想尽可能地限制需要完成的请求尽可能.

The main point is that I want to do only one request for this, as these requests are gonna be done from mobile devices that potentially have a slow internet connection, so I want to limit the requests that need to be done as much as possible.

我不确定这是否适合 RESTful 世界,但如果不适合,它会让我失望,因为这意味着我必须对 REST 的想法进行一些修改.

I'm not sure if this fits in the RESTful world, but if it doesn't, it will disappoint me, because it will mean I have to make a little hack on the REST idea.

有谁知道这样做的 RESTful 方式,或者不与 REST 理念冲突的漂亮方式?

Does anyone know of a RESTful way of doing this, or otherwise, a beatiful way that doesn't conflict with the REST idea?

推荐答案

客户是否需要在创作过程中提供任何信息?如果是这样,那么您真的需要将 GET 和 POST 分开,否则您需要使用每个 GET 发送该信息,这将非常难看.

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.

如果您发送的是没有任何附加信息的 GET,那么如果在返回资源之前资源不存在,则后端没有理由无法创建该资源.根据创建资源所需的时间,您可能想要考虑异步并按照其他答案使用 202,但这意味着您的客户端必须处理(还)另一个响应代码,因此可能会更好只是等待资源最终确定并返回.

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.

这篇关于获取资源的 RESTful 方式,但如果尚不存在则创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆