JSON返回错误请求-postcodes.io

时间:2018-11-26 14:28:36

标签: python json python-requests

我有这种方法:

import requests
import json

data = {  
    "postcodes" : ["AL1 2RJ", "AL9 5JP", "BN14 9GB", "BN16 3RT", "BN23 6QD", "BN3 7PN", "BN9 0AG", "BR5 3RP", "CM2 6XE","CM20 2SX","CR0 4NX","CT1 1DX",
    "CT1 3TQ", "CT10 2RQ", "CT16 3PS", "CT19 5SY", "DA1 4LD", "DA11 0DQ", "E4 8JA", "E6 6LG", "EN1 1TH", "EN9 1BY", "GU14 7QL", "GU19 5DG", "GU22 8BD",
    "GU34 2QS","GU7 1DR", "GU9 9QJ", "HA4 0LN", "HP11 1FY", "HP20 1DH", "HP3 9AA", "IG2 6BE", "KT12 2SS", "KT14 7NP", "LU1 3JH", "LU5 4XZ",
    "ME10 2XD", "ME20 7TP", "ME5 9SQ", "ME8 0PU", "MK1 1BN", "MK18 1TB", "N11 3PW", "NW1 9EX", "NW9 7TH", "PO19 7YH", "PO22 9NF", "PO3 5LZ",
    "PO9 1ND", "RG12 1EN", "RG2 0HB", "RG22 4TT", "RG30 1PR", "RG40 2NU", "RG41 5HH", "RH1 6QL", "RH11 7ST", "RH12 1HR", "RH15 9QT", "RH19 1QL",
    "RM20 3LP", "RM7 0AN", "RM9 6SJ", "SE1 5BA", "SE10 8DA", "SE26 4PU", "SE28 8RD", "SE7 7TZ", "SE9 5LT", "SG13 7RQ", "SL1 4XB", "SL6 1AY",
    "SS1 1PA", "SS13 3BY", "SS14 3AF", "SS2 6FW", "SS67UP", "SW11 3RX", "SW17 0BW", "SW20 0JQ", "TN14 5EW", "TN2 3FB", "TN23 7DH", "TN37 7PB",
    "TN40 2JS", "TW13 4EX", "TW8 8JW", "TW9 1YB", "UB4 0TU", "UB6 0UW", "UB8 2TE", "WD17 2SF", "WD6 4PR"]
    }

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
resp = requests.post('https://api.postcodes.io/postcodes/', data=data, headers=headers)
print(resp.json())

我运行此python myscript.py < myfile.json

{'status': 400, 'error': 'Invalid JSON submitted. You need to submit a JSON object with an array of postcodes or geolocation objects. Also ensure that Content-Type is set to application/json'}

但是请求似乎很好,这就是postcodes.io文档所说的:

Bulk Postcode Lookup

Accepts a JSON object containing an array of postcodes. Returns a list of matching postcodes and respective available data.

Be sure to submit JSON requests setting Content-Type to application/json

Accepts up to 100 postcodes.

POST
https://api.postcodes.io/postcodes

Post Data

This method requires a JSON object containing an array of postcodes to be posted, e.g.

{  
  "postcodes" : ["PR3 0SG", "M45 6GN", "EX165BL"]
}

This is the doc page

查询似乎很好,有什么主意吗?

2 个答案:

答案 0 :(得分:2)

您只需将data=data替换为json=data。这样就可以针对content-type=application/json进行验证了。

resp = requests.post('https://api.postcodes.io/postcodes/', json=data, headers=headers)

它将起作用。

答案 1 :(得分:1)

所以我有一个非常相似的问题,我正在努力将dataframe列转换为列表,然后转换为json对象。解决方案可能非常明显,但是我迷失在json.dumps()中,但这不是解决方案。以下工作:

import json
import requests
import pandas as pd

#imagine you have a csv, excel where you have the postcodes
create_sample={'Postcode': ['OL67UB', 'AB101QS']} 
df_postcodes=pd.DataFrame(create_sample)

list_postcodes=list(df_postcodes['Postcode'])

data = {  
        "postcodes" : list_postcodes
      }

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
resp = requests.post('https://api.postcodes.io/postcodes/', json=data, headers=headers)
print(resp.json())
相关问题