Problem sending post requests to spotify api in python - python

def queue_song(session_id):
song_uri='spotify:track:5RwV8BvLfX5injfqYodke9'
tokens = get_user_tokens(session_id)
headers = {'Content-Type': 'application/json',
'Authorization': "Bearer " + tokens.access_token,
}
url = BASE_URL +'player/queue'
data={
'uri':song_uri
}
response = requests.post(url,headers=headers,data=data).json()
print(response)
Output:
{'error': {'status': 400, 'message': 'Required parameter uri missing'}}
https://developer.spotify.com/documentation/web-api/reference/#/operations/add-to-queue
I dont thing there is any problem with auth tokens... coz 'GET' requests are working fine

By default, using data= in requests.post() sets the content type to application/x-www-form-urlencoded which makes the body a akin to a HTTP form request.
Spotify's API is JSON based, so your data needs to be a valid json data.
You can do it in 2 ways:
response = requests.post(url,headers=headers,data=json.dumps(data)).json()
Or, more simply:
response = requests.post(url,headers=headers,json=data).json()
and in this way you don't need to manually set the application/json header as well.
Edit:
After going through the API docs you linked, there's more wrong with the call you're making.
You're sending the parameters in data - which is the body of the request. But Spotify API specifies the parameters need to be put in the Query i.e. the query string of the URI. Which means your request should be:
response = requests.post(url,headers=headers,params=data).json() # set query string not body

Related

Why do I get error when simulating Ajax request with python

I am trying to simulate a web request using python library. This is the get request query created by the browser(I have replaced the actual url)
http://myurl.asp?treg=8338033&dob=14/09/2003&sid=0.3582164869592499
My code is here.
def individual(reg,dob):
session = Session()
myurl='http://myurl.asp'
# HEAD requests ask for *just* the headers, which is all you need to grab the
# session cookie
session.head('http://myurl')
response = session.get(
url=myurl,
data={
'treg': reg,
'dob': dob,
'sid':'0.4443253265244038'
},
headers={
'Referer': 'http://myurl.htm'
}
)
return response.text
It gives me invalid date response from server. But the same values sent through browser is successful. I have already tried yyyy-mm-dd format.
You are mixing up GET-style params with POST ones by using data instead of params in the request session.get call.
Python Request Post with param data

Swagger API and interaction with python requests

A product was purchased to enable our users to send/receive SMS over HTTP. Now it's my job to build it into our current CMS platform & database. It's got a swagger API.
Here is the documentation for the specific POST request I am trying to send:
POST: Send an SMS Message
Here is my simple python program to test the functionality. I get a generic 500 internal server error response. What am I doing incorrectly?
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
'Content-Type': 'application/json',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
'outgoing': 'true',
}
r=requests.post(url = API_URL, headers = headers, params = params)
print(r)
There seems to be 2 issues:
Content type and payload encoding.
You are using params parameter in the post method. params is used with get method for passing data in the URL's query string.
In the post method, depending on the required content type, you need to use either data parameter to send form-encoded data:
r=requests.post(url = API_URL, headers = headers, data = params)
or json parameter to send application/json payload:
r=requests.post(url = API_URL, headers = headers, json = params)
Remove the 'Content-Type' key from your headers dictionary. data and json parameters will set up correct content type automatically.
outgoing is not a valid request parameter for the /v1/conversations/messages resource. This field is from the response object, not the request one. Remove it from your payload.
So to sum up, for form-encoded payload the code should look like this:
import requests
API_URL = "https://api.kenect.com/v1/conversations/messages"
headers = {
'x-api-token': '****************',
'x-api-key': '*******************',
}
params = {
'contactPhone': '158572968**',
'locationId': '2045',
'messageBody': 'test sms',
}
r=requests.post(url = API_URL, headers = headers, data = params)

How to call an API using Python Requests library

I can't figure out how to call this api correctly using python urllib or requests.
Let me give you the code I have now:
import requests
url = "http://api.cortical.io:80/rest/expressions/similar_terms?retina_name=en_associative&start_index=0&max_results=1&sparsity=1.0&get_fingerprint=false"
params = {"positions":[0,6,7,29]}
headers = { "api-key" : key,
"Content-Type" : "application/json"}
# Make a get request with the parameters.
response = requests.get(url, params=params, headers=headers)
# Print the content of the response
print(response.content)
I've even added in the rest of the parameters to the params variable:
url = 'http://api.cortical.io:80/rest/expressions/similar_terms?'
params = {
"retina_name":"en_associative",
"start_index":0,
"max_results":1,
"sparsity":1.0,
"get_fingerprint":False,
"positions":[0,6,7,29]}
I get this message back:
An internal server error has been logged # Sun Apr 01 00:03:02 UTC
2018
So I'm not sure what I'm doing wrong. You can test out their api here, but even with testing I can't figure it out. If I go out to http://api.cortical.io/, click on the Expression tab, click on the POST /expressions/similar_terms option then paste {"positions":[0,6,7,29]} in the body textbox and hit the button, it'll give you a valid response, so nothing is wrong with their API.
I don't know what I'm doing wrong. can you help me?
The problem is that you're mixing query string parameters and post data in your params dictionary.
Instead, you should use the params parameter for your query string data, and the json parameter (since the content type is json) for your post body data.
When using the json parameter, the Content-Type header is set to 'application/json' by default. Also, when the response is json you can use the .json() method to get a dictionary.
An example,
import requests
url = 'http://api.cortical.io:80/rest/expressions/similar_terms?'
params = {
"retina_name":"en_associative",
"start_index":0,
"max_results":1,
"sparsity":1.0,
"get_fingerprint":False
}
data = {"positions":[0,6,7,29]}
r = requests.post(url, params=params, json=data)
print(r.status_code)
print(r.json())
200
[{'term': 'headphones', 'df': 8.991197733061748e-05, 'score': 4.0, 'pos_types': ['NOUN'], 'fingerprint': {'positions': []}}]
So, I can't speak to why there's a server error in a third-party API, but I followed your suggestion to try using the API UI directly, and noticed you're using a totally different endpoint than the one you're trying to call in your code. In your code you GET from http://api.cortical.io:80/rest/expressions/similar_terms but in the UI you POST to http://api.cortical.io/rest/expressions/similar_terms/bulk. It's apples and oranges.
Calling the endpoint you mention in the UI call works for me, using the following variation on your code, which requires using requests.post, and as was also pointed out by t.m. adam, the json parameter for the payload, which also needs to be wrapped in a list:
import requests
url = "http://api.cortical.io/rest/expressions/similar_terms/bulk?retina_name=en_associative&start_index=0&max_results=1&sparsity=1.0&get_fingerprint=false"
params = [{"positions":[0,6,7,29]}]
headers = { "api-key" : key,
"Content-Type" : "application/json"}
# Make a get request with the parameters.
response = requests.post(url, json=params, headers=headers)
# Print the content of the response
print(response.content)
Gives:
b'[[{"term":"headphones","df":8.991197733061748E-5,"score":4.0,"pos_types":["NOUN"],"fingerprint":{"positions":[]}}]]'

Starting a conversation with a chat bot hosted on Microsoft Azure through HTTP request in Python

A Microsoft tutorial shows that in order to set up a conversation with a bot I should issue the following HTTP request:
POST https://directline.botframework.com/api/conversations
Authorization: Bearer SECRET_OR_TOKEN
My question is if I can achieve this with the following Python code:
import requests
r = requests.post('https://directline.botframework.com/api/conversations',
params = {'Authorization':'Bearer ftmhNAqZ2tw.cwA.qIA.Xz2ZWfYJzxd8vJjcK9VmINWNLxlvKiM5jC8F_cbaf0s'})
If I print the response with print(r.content) it says:
{ "error": {
"code": "BadArgument",
"message": "Missing token or secret" } }
HTTP requests have three areas where content can be sent:
URL parameters
Body
Headers
To set these in python's requests package the following can be used (POST method assumed, but all are the same):
URL Parameters:
requests.post('https://myurl.com', params = {'MyParam':'MyValue'})
# equivilient to http://myurl.com?MyParam=MyValue
Body:
requests.post('https://myurl.com', data={"key":"value"})
# or if sending json data
requests.post('https://myurl.com', data=json.dumps(myData))
Headers:
requests.post('https://myurl.com', headers={"headername":"value"})
In your specific case, while the API is not well documented - we can assume they expect the "Authorization" data to be sent in a header, as this is standard. In this case, you need to assign headers as follows:
requests.post('https://directline.botframework.com/api/conversations', headers={'Authorization':'Bearer ftmhNAqZ2tw.cwA.qIA.Xz2ZWfYJzxd8vJjcK9VmINWNLxlvKiM5jC8F_cbaf0s'})
The bearer token needs to be sent as a header, not as a payload or query parameter.
You need to use the headers argument:
auth = {'Authorization': 'Bearer xxxYourBearerTokenHerexxx'}
r = requests.post('https://directline.botframework.com/api/conversations', headers=auth)
print(r) # <Response [200]>

Python requests Post request data with Django

I'm trying to send a simple post request to a very simple django server and can't wrap my head around why the post data isn't appearing in the requests post dictionary and instead its in the request body.
Client code:
payload = {'test':'test'}
headers = {'Content-type': 'application/json','Accept': 'text/plain'}
url = "localhost:8000"
print json.dumps(payload)
r = requests.post(url,data=json.dumps(payload),headers=headers)
Server Code:
def submit_test(request):
if request.method == 'POST':
print 'Post: "%s"' % request.POST
print 'Body: "%s"' % request.body
return HttpResponse('')
What is printed out on the server is:
Post: "<QueryDict: {}>"
Body: "{"test": "test"}"
I've played around with the headers and sending the data as a straight dictionary and nothing seems to work.
Any ideas? Thanks!!
The POST dictionary only contains the form-encoded data that was sent in the body of the request. The body attribute contains the raw body of the request as a string. Since you are sending json-encoded data it only shows up in the raw body attribute and not in POST.
Check out more info in the docs.
Try form-encoded data and you should see the values in the POST dict as well:
payload = {'test':'test'}
url = "localhost:8000"
requests.post(url, data=payload)
Specifying a user-agent in the headers should enable Django to interpret the raw data of the body and to correctly populate the POST dictionary. The following should work:
payload = {'test': 'test'}
url = "http://localhost:8000"
headers = {'User-Agent': 'Mozilla/5.0'}
requests.post(url, data=payload, headers=headers)
You should remove 'Content-type' from headers and use default one which is 'multipart/form-data'
response = client.post(
'/some_url/',
data={'post_key': 'some_value'},
# content_type='application/json'
)
If you uncomment 'content_type' data will be only in request.body

Categories

Resources