摘要:我有一个工作板,一个用户搜索一个邮政编码,并且显示与该邮政编码匹配的所有工作,我试图添加一项功能,使您可以查看该邮政编码一定英里范围内的工作。有一个Web API(www.zipcodeapi.com)可以进行这些计算并返回指定半径内的邮政编码,我不确定如何使用它。
使用www.zipcodeapi.com,输入一个邮政编码和一个距离,它会返回该距离内的所有邮政编码。 API请求的格式如下:https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units>
,因此,如果用户输入邮政编码“ 10566”且距离为5英里,则格式为https://www.zipcodeapi.com/rest/<api_key>/radius.json/10566/5/miles
,它将返回:
{
"zip_codes": [
{
"zip_code": "10521",
"distance": 4.998,
"city": "Croton On Hudson",
"state": "NY"
},
{
"zip_code": "10548",
"distance": 3.137,
"city": "Montrose",
"state": "NY"
}
#etc...
]
}
我的问题是如何使用django向API发送GET请求?
我让用户搜索了存储在zip = request.GET.get('zip')
中的邮政编码和存储在mile_radius = request.GET['mile_radius']
中的英里半径。如何将这两个值合并到https://www.zipcodeapi.com/rest/<api_key>/radius.<format>/<zip_code>/<distance>/<units>
中的相应位置并发送请求?可以使用Django完成此操作,还是让我感到困惑?是否需要使用前端语言来完成?我试图在Google上搜索此内容,但仅针对RESTful APIS找到它,我不认为这是我想要的。在此先感谢您的帮助,如果您无法确定我以前从未使用过Web API。
答案 0 :(得分:1)
您可以使用requests
包来完成您想要的事情。它非常简单,并且有很好的文档。
这是一个如何针对您的案例执行操作的示例:
zip_code = request.GET.get('zip')
mile_radius = request.GET['mile_radius']
api_key = YOUR_API_KEY
fmt = 'json'
units = 'miles'
response = requests.get(
url=f'https://www.zipcodeapi.com/rest/{api_key}/radius.{fmt}/{zip_code}/{mile_radius}/{units}')
zip_codes = response.json().get('zip_codes')
zip_codes
应该是一个数组,如您的示例中所述。