有人可以告诉我如何向Wit.ai消息api发出请求。我正在努力处理我的代码。
import requests
import json
import sys
from wit import Wit
# Wit speech API endpoint
API_ENDPOINT = 'https://api.wit.ai/message'
q='who are you'
# Wit.ai api access token
wit_access_token = 'B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
# defining headers for HTTP request
headers = {'authorization': 'Bearer ' + wit_access_token}
# making an HTTP post request
resp = requests.post(API_ENDPOINT, headers = headers,data = {'q':'who are you'})
# converting response content to JSON format
data = json.loads(resp.content)
print(data)
我要回来了:
{u'code': u'json-parse', u'error': u'Invalid JSON'}
答案 0 :(得分:3)
Wit API的/message
端点仅接受GET
方法,并且需要URL中的查询参数(请求体中不是data
)。 requests
库会在小写Authorization
标题字段中更正大小写,但根据the standard编写它是一个好习惯。此外,可以使用json()
上的Response
方法对JSON响应进行解码。
所有这一切:
import requests
API_ENDPOINT = 'https://api.wit.ai/message'
WIT_ACCESS_TOKEN = 'B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
headers = {'Authorization': 'Bearer {}'.format(WIT_ACCESS_TOKEN)}
query = {'q': 'who are you'}
resp = requests.get(API_ENDPOINT, headers=headers, params=query)
data = resp.json()
print(data)
但是请注意,Wit有一个Python library,它抽象了所有这些低级细节,使您的代码更简单,更易于阅读。使用它。
它看起来像这样(来自文档的example):
from wit import Wit
client = Wit(access_token=WIT_ACCESS_TOKEN)
resp = client.message('what is the weather in London?')
print('Yay, got Wit.ai response: ' + str(resp))