python-3.xrequest

'Error': 'JSON parse error - Expecting value: line 1 column 1 (char 0)' How do I fix this


I am writing a script to make requests from different web services. I am having problem when posting data from the json data below. When I run the patient_create_bill()function I get the logs below from response.

RESPONSE IS!!!!!
{'Error': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 0.0.0.0:9000
DEBUG:urllib3.connectionpool:http://0.0.0.0:9000 "POST /api/bill/patient/bills/ HTTP/1.1" 400 72
Creating Patient Bill .....................................

I have attempted to make a POST on post man I get 201 response meaning the payload is fine there is nothing wrong with it. enter image description here

This is my POST payload.
I have a separate file called mocks.py contains has PATIENT_BILL_CREATE_PAYLOAD

PATIENT_BILL_CREATE_PAYLOAD = {
    "bill_items": [{
        "item": "Syringes",
        "qty": 2,
        "description": "Medicorp syringes"
    }],
    "bill_services": [{
        "service": "Diagnosis",
        "service_type": "1",
        "duration": 5,
        "description": "diagnosis"
    }],
    "client": "Sandra Hernandez"
}

This is the function
i've imported the PATIENT_BILL_CREATE_PAYLOAD and using it in this function.

def patient_create_bill(headers):
    """This function uses login creds provided and returns token plus logged in user data."""
    url = "http://0.0.0.0:9000/api/bill/patient/bills/"
    data = PATIENT_BILL_CREATE_PAYLOAD
    res = requests.post(url, data=data, headers=headers)
    res_data = res.json()
    print("Creating Patient Bill .....................................\n")
    return res_data

Solution

  • Your own answer is right (encode your data to json), and here is the code fixed. This worked for me:

    instead of

    res = requests.post(url, data=data, headers=headers)
    

    the correct way to write it is...

    import json
    
    ...
    
    res = requests.post(url, data=json.dumps(data), headers=headers)
    
    # or
    
    res = requests.post(url, json=data, headers=headers)
    

    More info about this type of requests in requests library docs.