Theo75
Theo75

Reputation: 487

Python REST API call KO

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.\"}

enter image description here

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

Answers (2)

Vishal Singh
Vishal Singh

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

KilianAlias
KilianAlias

Reputation: 84

You need to put your token in the header, as per the curl request you showed.

Upvotes: 1

Related Questions