Error passing curl -d parameter in requests library

社会主义新天地 提交于 2021-01-29 07:13:59

问题


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


回答1:


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'))


来源:https://stackoverflow.com/questions/64147228/error-passing-curl-d-parameter-in-requests-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!