ditti
ditti

Reputation: 21

Connecting to API works using Shell but w/ Python requests lib throws 400 Client Error: Bad Request for url

I'm trying to connect to the Fluctuo (mobility data) GraphQL API with my access token. It works perfectly well using the curl Shell script, but it throws a 400 Client Error: Bad Request for url when trying the same using the Python requests library.

This is the curl script that works:

curl --request POST \
      --url https://flow-api.fluctuo.com/v1?access_token=MY_ACCESS_TOKEN \
      --header 'content-type: application/json' \
      --data '{"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n\t\tid\n  }\n}","variables":{"lat":48.856614,"lng":2.352222}}'

This is the Python code that throws the error:

url = "https://flow-api.fluctuo.com/v1?access_token=" + MY_ACCESS_TOKEN
head = {'content-type': 'application/json'}
query='''
query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n\t\tid\n  }\n}","variables":{"lat":48.856614,"lng":2.352222}'''

try:
    r = requests.post(url, json={'query': query},headers=head)
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Any ideas about what could go wrong is much appreciated.

Upvotes: 1

Views: 437

Answers (1)

ditti
ditti

Reputation: 21

I found the solution in the meantime: the POST data needed to be JSON-encoded. I dumped the query into JSON and this solved the issue. See code below.

import requests
import json

url = "https://flow-api.fluctuo.com/v1?access_token=" + MY_ACCESS_TOKEN
head = {'content-type': 'application/json'}
data = {"query":"query ($lat: Float!, $lng: Float!) {\n  vehicles(lat: $lat, lng: $lng) {\n\t\tid\n  }\n}","variables":{"lat":48.856614,"lng":2.352222}}

try:
    r = requests.post(url, data=json.dumps(data), headers=head)
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

r.status_code

Upvotes: 1

Related Questions