Reputation: 487
I have a problem calling a REST API.
A curl call works fine:
curl -X POST "https://pss-api.prevyo.com/pss/api/v1/sentiments" -H "accept: application/json" -H "Content-Type: application/json" -H "Poa-Token: xxxxxx" -d "{\"text\": \"Paul n'aime pas la très bonne pomme de Marie.\"}
It works fine also with the Postman.
But I get an error with the Python request.post()
:
import requests
api_key_emvista = "xxxx"
def call_api_emvista():
try:
full_url = "https://pss-api.prevyo.com/pss/api/v1/meaningrepresentation"
headers = {"Poa-Token" : api_key_emvista,
"Content-Type" : "application/json",
"accept" : "application/json"}
data = {"text" : "Paul aime la très bonne pomme de Marie."}
response = requests.post(full_url, data=data, headers=headers) #, verify=False)
return response.json()
except Exception as e:
print(e)
response = call_api_emvista()
response
{'timestamp': 1614608564801,
'status': 400,
'error': 'Bad Request',
'message': '',
'path': '/pss/api/v1/meaningrepresentation'}
Do you have an idea?
Upvotes: 1
Views: 148
Reputation: 6234
If you pass in a string instead of a dict
, that data will be posted directly.
data = '{"text": "Paul aime la très bonne pomme de Marie."}'
Instead of encoding the dict
yourself, you can also pass it directly using the json
parameter (added in version 2.4.2) and it will be encoded automatically.
def call_api_emvista():
try:
full_url = "https://pss-api.prevyo.com/pss/api/v1/meaningrepresentation"
headers = {
"Poa-Token": api_key_emvista,
"accept": "application/json",
}
data = {"text": "Paul aime la très bonne pomme de Marie."}
response = requests.post(
full_url, json=data, headers=headers
)
return response.json()
except Exception as e:
print(e)
Note, the json
parameter is ignored if either data
or files
is passed.
Using the json
parameter in the request will change the Content-Type
in the header to application/json
.
Upvotes: 2
Reputation: 84
You need to put your token in the header, as per the curl request you showed.
Upvotes: 1