POST request works in Postman but not in Python

后端 未结 1 1734
长发绾君心
长发绾君心 2021-01-18 11:15

When I make this POST request in Postman, I get the data. When I do it in Python 2.7 (using a Jupyter notebook), I get the error \"No JSON object could be decoded\". What am

1条回答
  •  鱼传尺愫
    2021-01-18 11:44

    Set json=payload and requests will add the headers you need:

    url = 'http://api.scb.se/OV0104/v1/doris/en/ssd/BE/BE0101/BE0101A/BefolkningNy'
    payload = ....
    
    
    r = requests.post(url, json=payload)
    

    That will give you your json:

    In [7]: 
       ...: r = requests.post(url, json=payload)
       ...: print(r.json())
       ...: 
    {u'data': [{u'values': [u'2054343'], u'key': [u'01', u'2010']}, {u'values': [u'2091473'], u'key': [u'01', u'2011']}], u'comments': [], u'columns': [{u'text': u'region', u'code': u'Region', u'type': u'd'}, {u'text': u'year', u'code': u'Tid', u'type': u't'}, {u'text': u'Population', u'code': u'BE0101N1', u'type': u'c'}]}
    

    If you happen to get an json.decoder.JSONDecodeError: Unexpected UTF-8 BOM (decode using utf-8-sig): error set the encoding to utf-8-sig:

    r = requests.post(url, json=payload)
    r.encoding = "utf-8-sig"
    print(r.json())
    

    0 讨论(0)
提交回复
热议问题