What to do when api returns html or json for different errors
<p>Using python requests to talk to the github api.</p>

<pre><code>response = requests.post('https://api.github.com/orgs/orgname/repos', auth, data)
</code></pre>

<p>If the request returns a 405 error I get HTML in the response.text</p>

<pre><code>&lt;html&gt;
&lt;head&gt;&lt;title&gt;405 Not Allowed&lt;/title&gt;&lt;/head&gt;
&lt;body bgcolor="white"&gt;
&lt;center&gt;&lt;h1&gt;405 Not Allowed&lt;/h1&gt;&lt;/center&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>If the request returns a 422 error I get JSON  in the response.text</p>

<pre><code>{"message":"Validation Failed","errors":        [{"resource":"Repository","code":"custom","field":"name","message":"name already exists on this account"}],"documentation_url":"https://developer.github.com/v3/repos/#create"}
</code></pre>

<p>Can I force the API to only return JSON?</p>

<p>If not, can I find out what type the response content will be?</p>

<p>In response to:</p>

<blockquote>
  <p>If not, can I find out what type the response content will be?</p>
</blockquote>

<p>If you want to know why github returns html rather than JSON for the API call, I can not answer that; however, to the answer to the above asked question, you can look at the "content" header of the http response.</p>

<pre><code>response = requests.post('https://api.github.com/orgs/orgname/repos', auth, data)
if "application/json" in response.headers['content-type']:
    print response.json()
</code></pre>

<p>In response to:</p>

<blockquote>
  <p>Can I force the API to only return JSON?
   you could try forcing the "Accept header within the request; however, this is down to GitHub server if it wants to serve json in the response</p>
</blockquote>

<pre><code>response = requests.post('https://api.github.com/orgs/omnifone/repos', auth=auth, data=data, headers={"Accept": "application/json"})
</code></pre>

python json http python-requests