Urls in restful webservices

*爱你&永不变心* 提交于 2019-12-25 00:26:19

问题


I have read this ebook and I've read that you should try to limit yourself to two base URLs. So if you have a quiz resouce you would have /quizes and /quizes/{id}. Then you use the HTTP verbs for actions. However how would you get a quiz from the server which is dynamically made with random questions when you try to follow this pattern?

I thougth of /quizes?type=random, but let say you want the type attribute to be optional defaulting to random and you already use the /quizes path for listing all saved quizes.

Creating a /quizes/generate?type=random path isn't following the advices, nor do I think the generate term fits in since it is a verb.

And are paths such as /quizes "reserved" to returning collections (I know REST isn't a spec) or is it perfectly legal to use /quizes for generating a quiz server side and returning it?

http://apigee.com/about/content/web-api-design


回答1:


What /quizzes should do is provide you a list of URL's that let you access different quizzes, so let's say you have defined that the media-type that /quizzes returns is JSON like so (maybe a specific type like application/json+quiz):

{ 
    quizzes = [
        { description: "Quiz 1", url: "/quizzes/1" },
        { description: "Quiz 2", url: "/quizzes/2" }
    ]
}

So what you can have is an entry that lets you access a random quiz, that can be something like this:

{ 
    quizzes = [
        { description: "Quiz 1", url: "/quizzes/1" },
        { description: "Quiz 2", url: "/quizzes/2" },
        { description: "Random", url: "/quizzes/random" },
    ]
}

The idea is that there is one REST endpoint, and all subsequent URL's are discovered through semantic media-types. So if your media-type specifies that there will be an entry with description Random that will give you a random quiz, then the endpoint consumer can use it.



来源:https://stackoverflow.com/questions/15908697/urls-in-restful-webservices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!