开发者

How to stay RESTful with a complex API

My setup: Rails 2.3.10, Ruby 1.8.7

I need to implement an API that is essentially a GET but depending on a date, could involve DELETE and POST actions as well. Let me explain, for a particular day, the API needs to add 10 items to one table randomly selected from another table but this is only done once a day. If the items added are from the previou开发者_运维问答s day, then the API needs to delete those items and randomly add 10 new ones. If multiple calls are made to the API in the same day, then it's just a GET after the initial creation. Hope this makes some sense.

How would I implement this as a RESTful API if at all possible.


How about?

GET /Items

If the next day has arrived, then generate 10 new items before returning them. If the next day has not arrived, then return the same 10 items you previously returned. There is no reason the server cannot update the items based on a GET. The client is not requesting an update so the request is still considered safe.


Not sure if I'm understanding you correctly, but just by looking at this, all I can think is the following: What a horrible thing, to perform an add which depending on what it's added, performs a delete. No disrespect, but seriously. Or maybe it is the way you are describing it.

Whatever the case, if you want to have a RESTful API, then you have to treat GET and PUT distinctively.

I don't think you have a clear use-case picture of how your API (or your system for that matter is to be done.) My suggestion would be to re-model this as follows:

Define a URI for your resource, say /random-items

  • a GET /random-items gets you between 0 and 10 items currently in the system.

  • a PUT/random-items with an empty body does the following:

    • delete any random items added on or before yesterday
    • add as many random items as necessary to complete 10
  • an invocation to DELETE /random-items) should return a 405 Method Not Allowed http error code.

  • an invocation to POST/random-items` should add no more than 10 items, deleting as needed.

  • /random-items/x is a valid URI so long as x is one of the items currently under /random-items.

    • A GET to it should return a representation for it or a 404 if it does not exist
    • A DELETE to it deletes it from under /random-items or 404 if it does not exist
    • A PUT to it should change its value if it makes sense (or return a 405)
    • A POST to it should return a 405 always

That should give you a skeleton sorta RESTful API.

However, if you insist, or need to overload GET so that it performs the additions and deletions behinds the scene, then you are making it non-RESTful.

That in itself is not a bad thing if you legitimately have a need for it (as no architectural paradigm is universally applicable.) But you need to understand what RESTful mean and when/why/how to break it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜