Using Python Requests to send file and JSON in single request

前端 未结 2 417
醉酒成梦
醉酒成梦 2020-12-30 06:30

I\'m trying to POST to an API (Build using SlimPHP) which accepts an image along with additional image meta data in the form of JSON.

I\'ve verified the API works

2条回答
  •  太阳男子
    2020-12-30 07:12

    Your problem is that you are using the image metadata as the source of key/value pairs to be posted. Instead of sending it as the value of one of those key/value pairs.

    The following code will send a request much like the curl statement you provided:

    url = 'my-url.com/api/endpoint'
    headers = {'Authorization': 'my-api-key'}
    image_metadata = {'key1': 'value1', 'key2': 'value2'}
    data = {'name': 'image.jpg', 'data': json.dumps(image_metadata)}
    files = {'file': (FILE, open(PATH, 'rb'), 'image/jpg', {'Expires': '0'})}
    r = requests.post(url, files=files, headers=headers, data=data)
    

提交回复
热议问题