Python Post call throwing 400 Bad Request

The problem in your code is, you set Content-Type header as application/json and not sending data in json format

 import httplib, json

 httpServ = httplib.HTTPConnection("127.0.0.1", 9100)
 httpServ.connect()
 headers = {"Content-type": "application/json"}
 data = json.dumps({
    "externalId": "801411",
    "name": "RD Core",
    "description": "Tenant create",
    "subscriptionType": "MINIMAL",
    "features": {
        "capture": False,
        "correspondence": True,
        "vault": False
    }
 })
 # here raw data is in json format
 httpServ.request("POST", "/tenants", data, headers)
 response = httpServ.getresponse()
 print response.status, response.reason
 httpServ.close()

Try using requests (install with pip install requests) instead of urllib.

Also, enclose your data as JSON in the request body, don't pass them as URL parameters. You are passing JSON data in your curl example as well.

import requests


data = {
    "externalId": "801411",
    "name": "RD Core",
    "description": "Tenant create",
    "subscriptionType": "MINIMAL",
    "features": {
        "capture": False,
        "correspondence": True,
        "vault": False
    }
}

response = requests.post(
    url="http://localhost:9100/tenants/",
    json=data
)

print response.status_code, response.reason

EDIT

From https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests:

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.

Tags:

Python

Rest

Curl