Alex
Alex

Reputation: 87

Converting cURL to Python with Requests

I'm having trouble accessing an API with Python. Here's my 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=payload, headers=headers)

print(r.text)

It returns 404 content but when I use cURL, it works and returns the json I'm looking for. This is the cURL line from the 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/

Upvotes: 0

Views: 98

Answers (2)

Grismar
Grismar

Reputation: 31389

Your problem is that the content passed on the cURL line is an assigned to conf of a JSON object, but you're passing in a Python dict to data.

This should work:

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)

And as remarked by @Laurent Bristiel, you need to POST instead of GET.

If you prefer to use a Python dict, you could also do this:

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)

Upvotes: 2

Laurent Bristiel
Laurent Bristiel

Reputation: 6935

The equivalent of a curl -F is a POST rather than a GET:

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

Upvotes: 0

Related Questions