File upload using REST API and Python requests

Hi, I ran into an issue uploading a file to an Omeka Classic instance using Python requests.
I tried to use code examples from here:

Those examples are for Omeka S, so I modified my code in terms of credentials, so my version looks like this:

 params = {
    'key': api_key
}

data = {
    "o:ingester": "upload", 
    "file_index": "0", 
    "o:item": {"o:id": item_id}
}

files = [
     ('data', (None, json.dumps(data), 'application/json')),
     ('file[0]', ('my_picture.jpg', open('my_picture.jpg', 'rb'), 'image/jpg'))
]

response = requests.post('http://my_omeca_site.com/api/files', params=params, files=files)

To which I receive an error message: Invalid request. Exactly one file must be uploaded per request.
Thing is, I am not trying to upload multiple files here. I thought, maybe it is somewhat different for Omeka Classic?
Any help would be appreciated.

The S and Classic APIs are totally different, basically. You can’t take an S example and use it for Classic, or vice-versa.

The “data” part is different, as well as the name of the file. The necessary structure to POST a new file is documented in the Omeka Classic developer docs.

Thanks. Yes, I had had a look at that post request description in the docs. My question was basically about translating it into Python Requests.
Seems like I have figured out how to do it, so here’s an example of my working code in case somebody has the same question.

import requests
import json

API_KEY = 'XXXXXXXXXXXXXXXXXXX'  # my Omeka API key


def upload_file(order, item_id):
    url = 'http://my_omeka_instanse.org/api/files'
    params = {'key': API_KEY}  # packing Omeka key as payload

    # Building data structure for the request
    body_data = {
            "order": order,  # order of the file, integer
            "item": {"id": item_id},  # ID of the item to which the file should be attached
            "element_texts": [
                {
                    "html": False,
                    "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",  # Title of the document
                    "element": {"id": 50}  # ID of the element responsible for title (50 in Dublin Core)
                }
            ]
        }
    data = {'data': json.dumps(body_data)}  # packing body data to json and assigning name 'data' to it

    # Building info about my file, assigning name 'file'
    files = {
        'file':('my_file.doc',
                open('my_file.doc', 'rb'),
                'application/msword')
    }
    response = requests.post(url, params=params, data=data, files=files)
    print(response.content)


if __name__ == '__main__':
    upload_file(3, 11)
1 Like