Python requests library: data vs json named arguments with requests.post

Viewed 3588

According to the relevant portion of the requests library documentation, the primary method to pass a dictionary to the post method is as follows:

r = requests.post(url, data = {"example": "request"})

Afterwards, the authors demonstrate an example of passing a JSON string directly to the Github API. Then the authors suggest that instead of encoding the dictionary as a JSON string and passing it via data, you can simply use the named parameter json to pass a dictionary in as follows.

r= requests.post(url, json = {"example": "request"})

When would you use json instead of data? Is this redundancy idiosyncratic or intentional?

2 Answers

Passing a dict to data causes the dict to be form-encoded, as though you were submitting a form on an HTML page; e.g., data={"example": "request"} will be sent in the request body as example=request. The json keyword, on the other hand, encodes its argument as a JSON value instead (and also sets the Content-Type header to application/json).

From the requests documentation, it seems that data was meant to be used for form submission, hence it is built to expect dict datatype and will process objects passed to this variable into a dict type if it can.

For example, if a nested json is passed to data:

{
      "ticker_symbol":ticker,
      "model_type":"2",
      "prediction":[
        {
          "epoch_time": 11111100000,
          "price": 12.00,
          "confidence_score": 0.6,
          "rate_of_error": 0.015,
        },
        {
          "epoch_time": 12112230000,
          "price": 13.00,
          "confidence_score": 0.7,
          "rate_of_error": 0.015,
        }
      ]
}

It will be "flattened" to become:

{
      "ticker_symbol":ticker,
      "model_type":"2",
      "prediction":[
          "epoch_time": 11111100000,
          "price": 12.00,
          "confidence_score": 0.6,
          "rate_of_error": 0.015,
          "epoch_time": 12112230000,
          "price": 13.00,
          "confidence_score": 0.7,
          "rate_of_error": 0.015,
      ]
}

Essentially although prediction is formatted as a json object with nested data, it will be transformed by requests.post() to become a key:[value] pair.

Related