Search code examples
pythonjsonhttppost

How do I use "format=json&data=" in post requests when developing in python?


format=json&data={
  "pickup_location": {
    "pin": "110096",
    "add": "address",
    "phone": "1111111111",
    "state": "Delhi",
    "city": "Delhi",
    "country": "India",
    "name": "name of pickup/warehouse location registered with delhivery"
  }
}

The data above is the payload of the post required on the API document.

I don't know how to transfer this data because of "format=json&data=".

payload = {
    "pickup_location": {
        "pin": "110096",``
        "add": "Changsha",  # address of warehouse
        "phone": "1111111111",
        "state": "Delhi",
        "city": "Delhi",
        "country": "India"
    }
}

payload = 'format=json&data={}'.format(payload)
r = requests.post(url_test, json=payload, headers=headers)
payload = {
    'format': 'json',
    'data': {
        "pickup_location": {
            "pin": "110096",
            "add": "Changsha",  # address of warehouse
            "phone": "1111111111",
            "state": "Delhi",
           "city": "Delhi",
           "country": "India"
        }
    }
}

payload = 'format=json&data={}'.format(payload)
r = requests.post(url_test, json=payload, headers=headers)

These are the two pieces of code I've tried.

The end result is the same: "format key missing in POST".

I also looked it up on the Internet, but I couldn't find the right answer.

So I came to ask for help, 3Q.


Solution

  • payload = {
        "pickup_location": {
            "pin": "110096",
            "add": "Changsha",
            "phone": "1111111111",
            "state": "Delhi",
            "city": "Delhi",
            "country": "India"
        }
    }
    
    payload = 'format=json&data={}'.format(payload).replace("'",'"')  # replace is very important
    r = requests.post(url_test, json=payload, headers=headers)
    

    Python strings default to double quotes on the outside and single quotes on the inside. But the api requires double quotes for the parameter key.