Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

rest - Restful URLs with data in query string or request body?

What's the rule of thumb for passing data in a REST URL in the query string vs. the body of a request?

Ie: You're creating a service to add hockey players. You could go with:

PUT /players 
{ "name": Gretzky }

or

PUT /players?name=Gretzky

If you're passing a lot of data, you would need to go with option #1 as there is a limit on the URL length. But other than this, why not just use the query string to pass data?


Update: Removed comment that you could test option #2 in a browser. Realized (duh) that you can only do GET-s in your browser.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Based on HTTP's definition of PUT, your first request is overwriting the list of players with a new list that contains just one player name. It is not adding to the list of players.

The second option does not really make much sense to me. Doing PUT without a body is not really consistent with the meaning of PUT.

Considering that one of the standard definitions of POST is to append to an existing resource, I'm not sure why you wouldn't do

POST /players 
{ "name": Gretzky }

If you are sure that all you player names are going to be unique then you could use PUT like this:

PUT /player/Gretzky
{ "name": Gretzky }

When you decide to do REST on HTTP you are agreeing to use HTTP in the way that is defined in RFC2616. That's what the uniform interface constraint means. And just to be pedantic, there is no such thing as a REST URL and you can't test either option in a browser because without javascript, you can't do a PUT in a browser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...