简体   繁体   中英

REST API for custom action other than PUT/POST/GET

I am writing a REST API that basically gives two resources: Users and Cars . With the API, you can POST/GET each resource.

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. It doesn't fit the model of 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). 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.

POST /cars
POST /ownerships

Well, "addNewCarToUser" is an action an therefore it breaches the resource principal.

I could think of

/user/:user_id/cars

This would be the resource to GET or POST.

I would perform a POST since this action will result in the creation of new data.

Not sure what naming convention you're using, but I would do something like this:

/users/:id/new_car # via POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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