Python requests.request returning garbage
17:07 12 Nov 2025

Calling an api. For almost all calls the response comes clean but for a few there is garbage in the returned json. Executing the garbage one in the Firefox browser with the same parameters returns clean json. Working code for testing:

import requests
headers = {
   'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0',
   'Accept': 'application/json, text/javascript, */*; q=0.01',
   'Accept-Language': 'en-US,en;q=0.8,pt-BR;q=0.5,pt;q=0.3',
   'Accept-Encoding': 'gzip, deflate, br, zstd',
   'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
   'X-Requested-With': 'XMLHttpRequest',
   'Origin': 'https://veiculos.fipe.org.br',
   'DNT': '1',
   'Sec-GPC': '1',
   'Connection': 'keep-alive',
   'Referer': 'https://veiculos.fipe.org.br/',
   'Cookie': 'ROUTEID=.5',
   'Sec-Fetch-Dest': 'empty',
   'Sec-Fetch-Mode': 'cors',
   'Sec-Fetch-Site': 'same-origin',
   'Priority': 'u=0',
   'TE': 'trailers',
}

def api_call(url, headers, parameters):
    try:
        r = requests.request('post', url, headers=headers, data=parameters)
        print (r.content)
        r_json = r.json()
        r.close()
        return r_json
    except Exception as e:
        print(repr(e))

url = 'https://veiculos.fipe.org.br/api/veiculos/ConsultarAnoModelo'
parameters = [('codigoModelo', 6906), ('codigoTabelaReferencia', 327), ('codigoTipoVeiculo', 1), ('CodigoMarca', 189)]
r_json = api_call(url, headers, parameters)
parameters = [('codigoModelo', 6340), ('codigoTabelaReferencia', 327), ('codigoTipoVeiculo', 1), ('CodigoMarca', 189)]
r_json = api_call(url, headers, parameters)

The second call always raises a JSONDecodeError because of initial the sequence \x8b\x15\x80 and the final sequence \x03

b'[{"Label":"2016 Gasolina","Value":"2016-1"},{"Label":"2014 Gasolina","Value":"2014-1"}]'
b'\x8b\x15\x80[{"Label":"2011 Gasolina","Value":"2011-1"}]\x03'
JSONDecodeError('Expecting value: line 1 column 1 (char 0)')

The buggy one executed in the browser:

enter image description here

Any ideas?

python json http python-requests