iskandarblue
iskandarblue

Reputation: 7526

Error passing curl -d parameter in requests library

I have a curl POST request that works perfectly in the terminal (macOS), returning a csv as expected. The following format is provided in the RJMetrcis documentation (see "Export figure data"). Here is the curl request in bash:

 curl -d "format=csv&includeColumnHeaders=1" -H "X-RJM-API-Key: myAPIkey" https://api.rjmetrics.com/0.1/figure/0000/export

My objective is to implement the exact same curl request in Python using requests. When I input the same parameters as a POST request, the code does not work returning an error:

import requests


headers = {'X-RJM-API-Key: myAPIkey'}
data= {'format=csv&includeColumnHeaders=1'}
url = "https://api.rjmetrics.com/0.1/figure/0000/export"

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

This returns the error:

TypeError: memoryview: a bytes-like object is required, not 'str'

On the second try:

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

returns

AttributeError: 'set' object has no attribute 'items'

What is the correct format in python for constructing a POST request so that it matches the data = {'key':'value'} convention, and returns a csv?Any help would be appreciated translating the bash curl POST into a python POST request

Upvotes: 0

Views: 453

Answers (1)

Alejandro Kaspar
Alejandro Kaspar

Reputation: 464

Here you are passing a set and you are expected to pass a dict or str object

data= {'format=csv&includeColumnHeaders=1'}

Replacing with

data= {'format':'csv&includeColumnHeaders=1'}

Should fix it.

On the other hand by seeing your curl request..

It all depends how you want to pass the data, following code (passing the data payload as a string) will post the data directly, that will be the equivalent to --data-raw in curl

import requests

url = "https://api.rjmetrics.com/0.1/figure/0000/export"

payload = "'{\"format\":\"csv&includeColumnHeaders=1\"}'"
headers = {
  'X-RJM-API-Key': 'myAPIkey'
}

response = requests.request("POST", url, headers=headers, data = payload)

print(response.text.encode('utf8'))

Upvotes: 3

Related Questions