开发者

Should the paramaters provided in a web service call be included in the response

Iv not got much experience with creating web services, however, I do spend 开发者_开发技巧a lot of time interfacing with them.

I wondered if there was a best practice that stated weather or not parameter that are provided in the request should be included in the response.

E.g.

Request:

a.com/getStuff?key=123

(JSON) Response:

{"key":"123",
 "value":"abc"}

or..

(JSON) Response:

 {"value":"abc"}

I much prefer the more verbose first option because it dos not enforce coupling between the request and the response. i.e. the response dosn't care what the request was, so you do not need to pass state around.

Is there a best practice?


If you are referencing a record in a database, or some other entity that is uniquely identified by an integer, GUID, or specifically-formatted string value, you should ALWAYS return that unique ID with the response, particularly if you are planning to allow the user to update that entity or reference it in a subsequent operation for creating related data or searching for related data.

If you are returning a derived value that may be a composite of many records' values, or of environmentally specific data (such as "How much free disk space is on my server?"), then the supplied parameters wouldn't mean anything in the response, and therefore shouldn't be returned.

Your point on coupling request-response is right on the money. If you are doing multiple simultaneous asynchronous calls, then the key value is very useful when handling the responses.


Referring to your example: I think id should always be part of the resource representation in your case JSON). The representation should be as self-explaining and self-referrable as possible. On top of an id-attribute/field I like also to use a link field:

{
    "id":123,
    "link":{
        "href":"http://api.com/item/123",
        "rel":"self"
    },
    otherData...
}

If your example GET /getStuff?key=123 is more a search (the parameter looks a bit like that) then it good to present the user a "summary" of your search:

{
    "items":[{
            item1...
        },
        {
            item2...
        }
    ],
    "submitted-params":{
        "key":"123",
        "other-param":"paramValue"
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜