REST API and delivering a binary resource

前端 未结 3 1416
长发绾君心
长发绾君心 2021-01-01 20:03

What is the convention to deliver a binary resource (like a pdf file) with a REST API? Do you just return a URL to the resource in your JSON or XML response, e.g., {\"url\"

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-01 20:31

    In my experience, doing that would antithetical to the idea of a REST webservice. You can never cache this response without serious headache, unlike traditionally RESTful services. Also, since you're going to have to be consuming the service as text in order to read your XML/JSON, you probably won't be able to optimize for both text and binary reads. Not to mention, you would have to always need the binary information, or you'd be taking a pretty significant hit in performance when you only wanted the text data. And if you always need the binary data, maybe ask yourself why you need the webservice at all?

    This is not to say it's impossible (there is BSON, after all) or that the use case for this is nonexistent, but you should make very sure that you can't get away with forcing a separate request for the binary data before you attempt to do this. Embedding binary data into a document format designed for text is very inefficient, and your data will be much larger in this form than if it were just raw bytes.

    As an aside, if you are always doing this with a vector graphic resource like SVG or certain types of PDFs, you can represent that as XML data. Again, you may not want to, as it will increase your payload, but it's an option to get around the "needing binary" thing.

提交回复
热议问题