简体   繁体   English

机智AI消息API

[英]Wit AI message API

Can someone please let me know how to make requests to Wit.ai message api. 有人可以让我知道如何向Wit.ai消息API发出请求。 I am struggling with my code. 我在为代码苦苦挣扎。

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)

I am getting back this: 我回来了:

{u'code': u'json-parse', u'error': u'Invalid JSON'}

The /message endpoint of Wit API accepts only GET method and expects the query parameters in URL (not data in request body). Wit API的/message端点仅接受GET方法,并且期望URL中的查询参数(而不是请求正文中的data )。 The requests library will correct the case on your lowercase Authorization header field, but it's a good practice to write it according to the standard . requests库将在小写的Authorization标头字段上更正大小写,但是根据标准编写它是一个好习惯。 Also, JSON response can be fetched decoded with json() method on Response . 另外,可以使用Response上的json()方法获取JSON响应解码。

With all of this: 所有这些:

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)

Note however, Wit has a Python library which abstracts all of these low-level details, and makes your code much simpler and easier to read. 但是请注意,Wit有一个Python库 ,该抽象了所有这些低级细节,并使您的代码更简单易读。 Use it. 用它。

It would look like this ( example from the docs): 看起来像这样(文档中的示例 ):

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM