Content-Type headers being overwritten in Flask Responses that already have a Content-Type header set

Author: CatarinaPBressanCreated Jul 1, 2017Updated Jul 29, 2026
Labelsbug

I have the following snippet that I expected to pass without errors:

python
import flask_restful
from flask import Flask


class Foo(flask_restful.Resource):
    def get(self):
        return "data"

app = Flask(__name__)
api = flask_restful.Api(app, default_mediatype=None)
api.representations = {}


@api.representation('application/octet-stream')
def stream_rep(data, status_code, headers=None):
    resp = app.make_response((str(data), status_code, headers))
    resp.headers['Content-Type'] = 'something/else'
    return resp

api.add_resource(Foo, '/')

with app.test_client() as client:
    res = client.get('/', headers=[('Accept', 'application/octet-stream')])
    assert res.status_code == 200
    print(res.content_type)
    assert res.content_type == 'something/else'

If I print the res.content_type, the content type will be set to the Accept's 'application/octet-stream' in the make_response method of the API class:

python
    def make_response(self, data, *args, **kwargs):
        default_mediatype = kwargs.pop('fallback_mediatype', None) or self.default_mediatype
        mediatype = request.accept_mimetypes.best_match(
            self.representations,
            default=default_mediatype,
        )
        (...)
        if mediatype in self.representations:
            resp = self.representations[mediatype](data, *args, **kwargs)
            resp.headers['Content-Type'] = mediatype
            return resp
        elif mediatype == 'text/plain':
            (...)

This is an issue when the API has to return the correct Content-Type for a media file (Images, videos, sounds, etc.), but instead unexpectedly returns the content-type of the accept header instead.

Source: flask-restful/flask-restful