How to design REST API for export endpoint?

可紊 提交于 2021-01-21 08:03:05

问题


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.

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.

So here's my first crack at it:

POST /api/alerts/export?format=csv

OR

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?

Thanks.


回答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.

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

GET /api/alerts
Accept: text/csv

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" 

(...)

Hope it helps you, Thierry



来源:https://stackoverflow.com/questions/33877541/how-to-design-rest-api-for-export-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!