title: How to determine if client expects a JSON response
body: <p>In my Werkzeug application I am intercepting all error responses and trying to respond with a JSON response if the client expects JSON or return the usual HTML page with 404 or 500:</p>
  
  <pre><code>def handle_error_response(self, environ, start_response, exc):
      if ('application/json' in environ.get('CONTENT_TYPE', '')
              and exc.get_response().content_type != 'application/json'):
          start_response('%s %s' % (exc.code, exc.name),
                         (('Content-Type', 'application/json'), ))
          return (json.dumps({"success": False, "error": exc.description}, ensure_ascii=False), )
      # go the regular path
      ...
  </code></pre>
  
  <p>In this solution I am relying on <code>Content-Type</code> header containing string<code>'application/json'</code>.</p>
  
  <p>However this doesn't look like a correct solution, because Wikipedia says:</p>
  
  <blockquote>
    <p><strong>Content-Type</strong> The MIME type of the body of the request (used with POST and PUT requests)</p>
  </blockquote>
  
  <p>Is it a good strategy to check if <code>'text/html'</code> is inside header <code>Accept</code> and then return HTML response otherwise return JSON response?</p>
  
  <p>Any other more robust solutions?</p>
  
  <p>When Chrome requests an HTML page header</p>
  
  <pre><code>Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
  </code></pre>
  
  <p>is sent, when Ember makes an API request</p>
  
  <pre><code>Accept: application/json, text/javascript, */*; q=0.01
  </code></pre>
  
  <p>is sent.</p>
  
  <p>Maybe <code>X-Requested-With: XMLHttpRequest</code> should be taken into account?</p>