使用请求将cURL转换为Python
使用Python访问API时遇到问题。下面是我的Python:使用请求将cURL转换为Python,python,python-requests,Python,Python Requests,使用Python访问API时遇到问题。下面是我的Python: import requests url = 'https://bigjpg.com/api/task/' payload = {'style': 'photo', 'noise': '3', 'x2': '1', 'input': 'https://www.example.com/photo.jpg'} headers = {'X-API-KEY': 'xyz123'} r = requests.get(url, data=pa
import requests
url = 'https://bigjpg.com/api/task/'
payload = {'style': 'photo', 'noise': '3', 'x2': '1', 'input': 'https://www.example.com/photo.jpg'}
headers = {'X-API-KEY': 'xyz123'}
r = requests.get(url, data=payload, headers=headers)
print(r.text)
它返回404内容,但当我使用cURL时,它工作并返回我正在寻找的json。这是API中的卷曲线:
curl -F 'conf={"style": "photo", "noise": "3", "x2": "1", "input": "https://www.example.com/photo.jpg"}' -H 'X-API-KEY:xyz123' https://bigjpg.com/api/task/
与curl-F的等价物是POST而不是GET:
r = requests.post(url, data=payload, headers=headers)
与curl-F的等价物是POST而不是GET:
r = requests.post(url, data=payload, headers=headers)
您的问题是,在cURL行上传递的内容被分配给JSON对象的
conf
,但您正在将Python dict传递给数据
这应该起作用:
import requests
url = 'https://bigjpg.com/api/task/'
payload = 'conf={"style": "photo", "noise": "3", "x2": "1", "input": "https://www.example.com/photo.jpg"}'
headers = {'X-API-KEY': 'xyz123'}
r = requests.post(url, data=payload, headers=headers)
print(r.text)
正如@Laurent Bristiel所说,你需要发布而不是获取
如果您喜欢使用Python dict,也可以这样做:
import requests
import json
url = 'https://bigjpg.com/api/task/'
conf = {'style': 'photo', 'noise': '3', 'x2': '1', 'input': 'https://www.example.com/photo.jpg'}
payload = f'conf={json.dumps(conf)}'
headers = {'X-API-KEY': 'xyz123'}
r = requests.post(url, data=payload, headers=headers)
print(r.text)
您的问题是,在cURL行上传递的内容被分配给JSON对象的conf
,但您正在将Python dict传递给数据
这应该起作用:
import requests
url = 'https://bigjpg.com/api/task/'
payload = 'conf={"style": "photo", "noise": "3", "x2": "1", "input": "https://www.example.com/photo.jpg"}'
headers = {'X-API-KEY': 'xyz123'}
r = requests.post(url, data=payload, headers=headers)
print(r.text)
正如@Laurent Bristiel所说,你需要发布而不是获取
如果您喜欢使用Python dict,也可以这样做:
import requests
import json
url = 'https://bigjpg.com/api/task/'
conf = {'style': 'photo', 'noise': '3', 'x2': '1', 'input': 'https://www.example.com/photo.jpg'}
payload = f'conf={json.dumps(conf)}'
headers = {'X-API-KEY': 'xyz123'}
r = requests.post(url, data=payload, headers=headers)
print(r.text)
我还必须在标题中添加“Content-Type”:“application/x-www-form-urlencoded”
。谢谢我还必须在标题中添加“Content-Type”:“application/x-www-form-urlencoded”
。谢谢