简体   繁体   中英

python-requests and EchoSign

I am trying to post a file into EchoSign APIs and it works everywhere for me except for python-requests.

I have here the CURL command that works perfectly

curl -H "Access-Token: API_KEY" \
 -F File=@/home/user/Desktop/test123.pdf \
 https://secure.echosign.com/api/rest/v2/transientDocuments

and this is my requests function. It will upload the PDF file but with garbage whereas CURL works perfectly.

api_url = 'https://secure.echosign.com/api/rest/v2'

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

   :param access_token: EchoSign Access Token
   :param file_path: Absolute or relative path to File
   :return string: Document ID

   """
    headers = {'Access-Token': access_token}

    url = api_url + '/transientDocuments'

    with open(file_path, 'rb') as f:
        files = {
            'File': f,
        }
        return requests.post(url, headers=headers, files=files).json().get('transientDocumentId')

What am I doing wrong?? I have tried posting the file as data instead of files too and still no different result

Thanks

EDIT

It worked when I added

data = {
    'Mime-Type': 'application/pdf',
    'File-Name': 'abc.pdf'
}

So, my new function would be:

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

    :param access_token: EchoSign Access Token
    :param file_path: Absolute or relative path to File
    :return string: Document ID

    """
    headers = {
        'Access-Token': access_token,
    }
    data = {
        'Mime-Type': 'application/pdf',
        'File-Name': 'abc.pdf'
    }
    url = api_url + '/transientDocuments'
    files = {'File': open(file_path, 'rb')}
    return requests.post(url, headers=headers, data=data,
                         files=files).json().get('transientDocumentId')

This is how it works

def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

    :param access_token: EchoSign Access Token
    :param file_path: Absolute or relative path to File
    :return string: Document ID

    """
    headers = {
        'Access-Token': access_token,
    }
    data = {
        'Mime-Type': 'application/pdf',
        'File-Name': 'abc.pdf'
    }
    url = api_url + '/transientDocuments'
    files = {'File': open(file_path, 'rb')}
    return requests.post(url, headers=headers, data=data,
                         files=files).json().get('transientDocumentId')

Try passing in the filename and mime-type, like so:

files = {
    'File': (
        os.path.basename(file_path),
        f,
        'application/pdf',
    )
}

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM