【问题标题】:Is my API response good enough?我的 API 响应是否足够好?
【发布时间】:2013-11-11 11:54:58
【问题描述】:

我正在制作一个 API,以允许其他人将我们的服务集成到他们自己的系统中。

找到制定回应的最佳方式并不容易 - 我见过很多不同的方法。很多时候它做得很差,我和其他人很难使用它。

这就是我的做法:

<xml>
    <HttpResponse>200</HttpResponse>
    <data>
        <report>
            <id>200</id>
            <date>07.03.2013 11:13:00</date>
            <title>Fake report 1</title>
            <content>Lorem ipsum dolor sit amet.</content>
        </report>
        <report>
            <id>448</id>
            <date>10.04.2013 12:13:34</date>
            <title>Fake report 2</title>
            <content>Lorem ipsum dolor sit amet.</content>
        </report>
        <report>
            <id>927</id>
            <date>25.10.2013 11:49:34</date>
            <title>Fake report 3</title>
            <content>Lorem ipsum dolor sit amet.</content>
        </report>
    </data>
</xml>

如果出现错误,则 HttpResponse 将给出正确的代码来表示这一点,并且数据将包含错误的描述,如下所示:

<xml>
    <HttpResponse>418</HttpResponse>
    <data>
        <error>
            <code>AB43</code>   /* <<-- this code says what I can search for in the code to find the exact process/line where it failed */
            <description>You are the one who messed up!!!</description>
        </error>
    </data>
</xml>

我的问题很简单:这个回答有意义吗?

有没有我没有考虑到的情况?

人们在从这样的响应中检索数据时会遇到问题吗?

我还能怎么做?

顺便说一句:我不会使用 JSON,讨论结束!

【问题讨论】:

  • 我会将错误节点向上移动到根级别,而不是在数据节点下。所以你要么得到一个错误,要么得到数据。在我看来,它更容易理解和检查。我会使用 JSON ;-)
  • @RotemHermon JSON 在冗长方面很有意义。最终,这两种技术都是为非常相似的目标而设计的。在功能上,差别不大。
  • 除了代码和描述之外,为错误添加一个名称,例如“索引超出范围”,它是恒定的,可以通过字符串相等性检查。然后在描述中,添加可以变化的细节,因此不能用字符串相等性检查,例如“最大允许索引为 35,但提供的索引为 37”。这将使最终必须处理错误的代码更易于阅读和编写。
  • @RotemHermon 我认为,你是对的;一个错误并不是真正的“数据”,所以它应该只是替换它。谢谢!我可能会同时使用 XML 和 JSON,并允许人们选择,但我想先完成整个事情。底部注释只是为了避免 cmets 和仅包含“使用 JSON”的答案,因为这不能回答我的问题。
  • @RotemHermon 我已经看到大多数开发人员更喜欢 JSON 而不是 XML,但是 XML 不是更好吗,因为它允许嵌套元素和整体更深入的功能?

标签: xml api response httpresponse error-code


【解决方案1】:

基于 cmets 显示错误的新方法。

我不想将错误向上移动并替换“数据”,因为我想保留出现多个错误的可能性。相反,我将“数据”更改为“错误”。

<xml>
    <HttpResponse>418</HttpResponse>
    <errors>
        <error>
            <code>AB43</code>
            <title>document_title_too_long</title>
            <description>The title is limited to 64 characters, yours was 73. </description>
        </error>
        <error>
            <code>AC85</code>
            <title>document_no_category</title>
            <description>You must select a category to save the document. </description>
        </error>
    </errors>
</xml>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-19
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多