Wit AI message API - python

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'}

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

Related

Spotify Web API not detecting body of POST request

I'm currently working on an app, one functionality of it being that it can add songs to the user's queue. I'm using the Spotify API for this, and this is my code to do so:
async def request():
...
uri = "spotify:track:5QO79kh1waicV47BqGRL3g" # temporary, can change later on
header = {'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "{} {}".format(TOKEN_TYPE, ACCESS_TOKEN)}
data = {'uri': uri}
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue", data=data, headers=header)
...
I've tried a lot of things but can't seem to understand why I'm getting Error 400 (Error 400: Required parameter uri missing).
so the Spotify API for the endpoint you're using suggests that the uri parameter required should be passed as part of the url, instead of as a data object.
Instead of data = {'uri': uri} can you please try adding your uri to the end of the url as such:
resp = requests.post(url="https://api.spotify.com/v1/me/player/queue?uri=?uri=spotify%3Atrack%3A5QO79kh1waicV47BqGRL3g", headers=header)
I also suggest using software like postman or insomnia to play around with the requests you send.

Using JSON data from API GET to POST to another API via python script

So, I'm new to python and am struggling, self taught, and still learning to code. So be easy on me :)
I am using a script to get data from one source (Jira's API) and trying to use those results to post to another (PowerBi).
I've managed to successfully get the data, I just don't know how to pass the data to this other API.
I know how to use the GET and POST calls, it's just using the data from one to another than I can't seem to find anything about. Assuming since what I'm asking for is very specific?
edit: I also want to mention that while my get is asking for specific data, I'm getting more than I actually need. So I need a way to specify (hopefully) what data is actually being sent to PowerBi's API
import json
import requests
url = 'https://mydomain.atlassian.net/rest/api/2/search'
headers = { 'Content-Type' : 'application/json',
'Authorization' : 'Basic 123456789' }
params = {
'jql' : 'project IN (, PY, CH, NW, RP, DP, KR, DA, RE, SS, CR, CD, AB) AND issueType=incident AND statusCategory!=Done',
'startAt': 0,
'maxResults' : 50,
}
requestget = requests.get(url, headers=headers, params=params)
if requestget.status_code == 200:
print(json.dumps(json.loads(requestget.text), sort_keys=True, indent=4, separators=(",", ": ")))
else:
print("None")
Apologies if I miss understood what you were asking help on, but you could use this to send a POST request as json.
request = urllib.request.Request()#Put the powerbi api here
request.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = #your json data
jsonBytes = jsondata.encode('utf-8')
#Has to be bytes
request.add_header('Content-Length', len(jsonBytes))
response = urllib.request.urlopen(request, jsonBytes)
You could go with a requests.post instead.
jsondata = #put json data here
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(jsondata), headers=headers)
Requests documentation

Post array as parameters for API call

I am trying to send a tweet to the Buffer API using the POST /updates/create method. I get a 405 error as a response. I think the problem comes from the profile_ids parameter which should be an array. What is the correct syntax for this case ?
import requests
import json
url = "https://api.bufferapp.com/1/updates/create.json"
params = dict()
params['access_token'] = myToken
params["profile_ids"] = myID
params['text']= "This is a test"
r = requests.post(url, params=params)
print(r.status_code)
Please note that myToken and myID are variables I did not share for the post.

Error "400 Bad request" when sending JSON object to an api using Python

Here is a snippet of code:
api_url = {url}
auth_head = {key: value} << my api authentication header
data = {'title':'Python'} << the valid json object format that the api accepts
Here is what I tried:
data = json.dumps(data)
json_obj = json.loads(data)
response = requests.post(api_url, headers = auth_head, data = json_obj)
print(response.text)
Here is the output:
"400 Bad request"
To make sure the url and my api token key work I tried GET:
response = requests.get(api_url, headers = auth_head)
print(response.status_code)
Output:
"200"
So the url and api token work fine. I feel I am not sending the correct json object construct that the api wants
You don't need to send data as json. Just send data as dictionary. It will accept. requests automatically will encode your dictionary to json

Flask Testing a put request with custom headers

Im trying to test a PUT request in my Flask app, using flasks test client.
Everything looks good to me but i keep getting 400 BAD request.
I tried the same request using POSTMAN and I get the response back.
Here is the code
from flask import Flask
app = Flask(__name__)
data = {"filename": "/Users/resources/rovi_source_mock.csv"}
headers = {'content-type': 'application/json'}
api = "http://localhost:5000/ingest"
with app.test_client() as client:
api_response = client.put(api, data=data, headers=headers)
print(api_response)
Output
Response streamed [400 BAD REQUEST]
You do need to actually encode the data to JSON:
import json
with app.test_client() as client:
api_response = client.put(api, data=json.dumps(data), headers=headers)
Setting data to a dictionary treats that as a regular form request, so each key-value pair would be encoded into application/x-www-form-urlencoded or multipart/form-data content, if you had used either content type. As it is, your data is entirely ignored instead.
I think it is simpler to just pass the data using the json parameter instead of the data parameter:
reponse = test_client.put(
api,
json=data,
)
Quoting from here:
Passing the json argument in the test client methods sets the request
data to the JSON-serialized object and sets the content type to
application/json.

Categories