[英]Can a RESTful service return both JSON and XML for the same resource, depending on the request header?
I have a simple RESTful method which currently returns JSON representation of an object. 我有一个简单的RESTful方法,它当前返回一个对象的JSON表示。
My question is more of from the architectural perspective and not completely technical. 我的问题更多的是从架构的角度而不是完全技术性的。
Should a RESTful service be designed in such a way that it returns both JSON and XML at the same time? 是否应该以这样的方式设计RESTful服务,使其同时返回JSON和XML?
As far as I know this is a bad practice and separate resources should be defined for this. 据我所知,这是一种不好的做法,应该为此定义单独的资源。 One resource should return JSON data and other one XML. 一个资源应返回JSON数据和其他一个XML。
Am I thinking it correctly? 我是否正确思考?
The same resource may return either XML or JSON depending upon the request, but it shouldn't return both at the same time. 根据请求,相同的资源可能返回XML或JSON,但它不应同时返回两者。 You will know which one to return based upon the request, so there is no need to generate both -- just generate the one you'll be returning. 您将根据请求知道要返回哪一个,因此无需生成两者 - 只需生成您将返回的那个。
Here is how you might choose to decide which to return. 以下是您可以选择决定返回的方式。 Evaluate in order, stopping when you've determined the format to return: 按顺序评估,在确定要返回的格式时停止:
GET /user/1234.json
or GET /user/1234.xml
), use that as the requested format. 如果已将扩展添加到资源( GET /user/1234.json
或GET /user/1234.xml
), GET /user/1234.xml
其用作请求的格式。 No. The way you represent your resource should be defined by what your clients expect (there is a http-header to say what representations the client accept). 不可以。您表示资源的方式应根据客户的期望来定义(有一个http-header表示客户接受的表示形式)。 This means your server should check what is the representation the current client accepts and send the response in this representation (or send a response that says he cannot represent the resource in that media-type) 这意味着您的服务器应该检查当前客户端接受的表示形式,并以此表示形式发送响应(或发送一个响应,表明他不能代表该媒体类型中的资源)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.