Joe
Joe

Reputation: 13141

Python 2 - post request with data

I am working on an API that can work with Curl and command looks like this:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' --header 'api_key: someKey' -d '{
  "configurationPath": "/a/b",
  "entityTypesFilter": [
    "Filter1"
  ],  
  "pageSize": 10 
}' 'http://localhost:123/ab/rest/v1/entities'

How to translate that into a Python 2 code with request library?

I tried something like:

import requests
headers = {'api_key': 'someKey'}
url = "http://localhost:123/ab/rest/v1/entities"

data = {
  "configurationPath": "/a/b",
  "entityTypesFilter": [
    "Filter1"
  ],  
  "pageSize": 10 
}

r = requests.post(url, headers=headers, data = data)
print r.content

but that gives 415 error:

> Status Report</p><p><b>Message</b> Unsupported Media Type</p><p><b>Description</b> The origin server is refusing to se
rvice the request because the payload is in a format not supported by this method on the target resource.</p><hr class="
line" /><h3>Apache Tomcat/9.0.8</h3></body></html>

How to fix it? I believe it is format of a data part but not sure what is expected and how to modify to make it works.
Thanks.

Upvotes: 0

Views: 174

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600041

Your curl command is sending the data as JSON with the application/json content-type; your Python code is not doing that.

requests will do this if you use the json parameter instead of data:

r = requests.post(url, headers=headers, json=data)

Upvotes: 2

Related Questions