user3289968
user3289968

Reputation: 97

Wit AI message API

Can someone please let me know how to make requests to Wit.ai message 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'}

Upvotes: 0

Views: 1063

Answers (1)

randomir
randomir

Reputation: 18697

The /message endpoint of Wit API accepts only GET method and expects the query parameters in URL (not data in request body). 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. Also, JSON response can be fetched decoded with json() method on Response.

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

Upvotes: 3

Related Questions