如何为导出端点设计 REST API? [英] How to design REST API for export endpoint?

查看:29
本文介绍了如何为导出端点设计 REST API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设计 REST API,但遇到了设计问题.我有 alerts,我希望用户能够export 到少数文件格式之一.所以我们已经开始使用 export 来处理动作/命令,这感觉就像 RPC 而不是 REST.

I am designing a REST API and am running into a design issue. I have alerts that I'd like the user to be able to export to one of a handful of file formats. So we're already getting into actions/commands with export, which feels like RPC and not REST.

此外,我不想假设默认文件格式.相反,我想要求提供它.我不知道如何设计 API 来做到这一点,我也不知道如果没有提供所需的参数,我也不知道返回什么响应代码.

Moreover, I don't want to assume a default file format. Instead, I'd like to require it to be provided. I don't know how to design the API to do that, and I also don't know what response code to return if the required parameter isn't provided.

这是我第一次尝试:

POST/api/alerts/export?format=csv

POST/api/alerts/export/csv

此端点是否按照您的方式设置?它是否以正确的方式设置来要求文件格式?如果未提供所需的文件格式,要返回的正确状态代码是什么?

Is this endpoint set up the way you would? And is it set up in the right way to require the file format? And if the required file format isn't provided, what's the correct status code to return?

谢谢.

推荐答案

实际上,您应该考虑使用 HTTP 内容协商(或 CONNEG)来执行此操作.这利用了 Accept 标头(请参阅 HTTP 规范:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1) 指定响应的预期媒体类型.

In fact you should consider HTTP content negotiation (or CONNEG) to do this. This leverages the Accept header (see the HTTP specification: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1) that specifies which is the expected media type for the response.

例如,对于 CSV,你可以有这样的东西:

For example, for CSV, you could have something like that:

GET /api/alerts
Accept: text/csv

如果您想指定其他提示(文件名,...),服务器可以返回 Content-Disposition 标头(请参阅 HTTP 规范:http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1) 在响应中,如下所述:

If you want to specify additional hints (file name, ...), the server could return the Content-Disposition header (see the HTTP specification: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1) in the response, as described below:

GET /api/alerts
Accept: text/csv

HTTP/1.1 200 OK
Content-Disposition: attachment; filename="alerts.csv" 

(...)

希望对你有帮助蒂埃里

这篇关于如何为导出端点设计 REST API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆