简体   繁体   English

用于PUT / POST / GET以外的自定义操作的REST API

[英]REST API for custom action other than PUT/POST/GET

I am writing a REST API that basically gives two resources: Users and Cars . 我正在编写REST API,它基本上提供了两种资源: UsersCars With the API, you can POST/GET each resource. 使用API​​,您可以POST / GET每个资源。

But now I have a custom action that will basically give a new car to a user. 但现在我有一个自定义动作,基本上会给用户一个新车。 This will require a cron job in the back end and do the operation. 这将需要后端的cron作业并执行操作。 It doesn't fit the model of POST/PUT. 它不适合POST / PUT模型。 I am just wondering what's the best route for this? 我只是想知道这是什么最好的路线?

I thought of: 我想到了:

/addNewCarToUser/:user_id

I know this question is too localized but I am just wondering if it's just a judgment call or if there's a convention for this type of request? 我知道这个问题过于局部化但我只是想知道这只是一个判断调用,还是有这种请求的约定? Thanks 谢谢

It depends. 这取决于。 Do cars only exist if they belong to users? 如果汽车属于用户,它们是否只存在? Or can they exist on their own? 或者他们可以自己存在吗?

If they are only in the context of belonging to a User, I would just have Cars belong to Users and have a route like this to create a new one: 如果它们只属于属于用户的环境,我只会让汽车属于用户并拥有这样的路线来创建一个新的:

POST /users/:id/cars

Or you can specify who the owner by a car has_one owner (seems counterintuitive, but data-wise a car often has 0 or 1 owner). 或者您可以指定汽车拥有者拥有者的所有者(似乎违反直觉,但数据方面,汽车通常拥有0或1个所有者)。 The route could be: 路线可能是:

POST /cars?user_id=######

Another sensible relation would be to have a third resource Ownerships, and then you could create a new car and then a new ownership, because creating a car and giving it to a user would be 2 new resources. 另一个合理的关系是拥有第三个资源所有权,然后你可以创建一个新车然后新的所有权,因为创建一辆汽车并将其交给用户将是2个新资源。

POST /cars
POST /ownerships

Well, "addNewCarToUser" is an action an therefore it breaches the resource principal. 好吧,“addNewCarToUser”是一个动作,因此它违反了资源主体。

I could think of 我能想到

/user/:user_id/cars /用户/:USER_ID /汽车

This would be the resource to GET or POST. 这将是GET或POST的资源。

I would perform a POST since this action will result in the creation of new data. 我会执行POST因为此操作将导致创建新数据。

Not sure what naming convention you're using, but I would do something like this: 不确定你正在使用什么命名约定,但我会做这样的事情:

/users/:id/new_car # via POST

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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