Home > Back-end >  Cloud Functions with Requests return 'Could not parse JSON' error
Cloud Functions with Requests return 'Could not parse JSON' error

Time:01-08

I'm running a cloud function in python to return some data from an api. The function is not executed and I have the error {'code': 400, 'message': 'Could not parse JSON'}.

Here is my code:

import requests
import json

def my_function(request):

    url = 'https://blablabla/detailed'
    headers = {'X-Api-Key': 'XXXXXXXX',
           'content-type': 'application/json'}

    data = '{"dateRangeStart":"2020-05-10T00:00:00.000","dateRangeEnd":"2020-05-16T23:59:59.000","amountShown": "HIDE_AMOUNT","detailedFilter":{ "page":"1","pageSize":"50"}}'
    
    #req = requests.post(url, headers=headers, json=data)
    req = requests.post(url, headers=headers, data=json.dumps(data))
    print(req.json())

how should I format my data variable?

CodePudding user response:

Just give your dict as your json argument, you don't need to specify the content-type headers requests will do it for you.

import requests


def my_function(request):
    url = 'https://blablabla/detailed'
    headers = {'X-Api-Key': 'XXXXXXXX', }

    data = {"dateRangeStart": "2020-05-10T00:00:00.000", "dateRangeEnd": "2020-05-16T23:59:59.000", "amountShown": "HIDE_AMOUNT", "detailedFilter": { "page": "1", "pageSize": "50", }, }
    
    req = requests.post(url, headers=headers, json=data)
    print(req.json())

If you do not set a content-type header will try to set it for you:

  • When using the keyword argument json: it will set it to application/json
  • When using the keyword argument data (and the value passed respects some criteria, most of the time you don't have to worry about it): it will set it to application/x-www-form-urlencoded
  • If both kwargs are present data takes priority for the header so it will be set to application/x-www-form-urlencoded

I have not detailed the behaviour when the kwarg files is used as it would be really lengthy and is out of scope here.

Here's the source code.

  •  Tags:  
  • Related