Search code examples
pythonapicurlpostmultipartform-data

How to pass multipart/form-data into Python POST Request


I am trying to translate this curl command into a python POST request. I am new to calling api endpoints and this is my first encounter of -F form data. The curl request I am trying to replicate is below:

curl -X POST "https://genericurl.com/rest/endpoint" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "strictQuotes=" -F "escape=\"" -F "continueOnError=" -F "separator=;" -F "deleteFile=" -F "simulation=" -F "fileName=synchronization_file" -F "headerRow=" -F "ignoreLeadingWhitespace=" -F "sendNotification=" -F "fileId=" -F "template=" -F "saveResult=" -F "batchSize=1000" -F "file=@testSourceFile.csv;type=text/csv" -F "quote=\""

Thank you in advance!


Solution

  • There is a nice tool which helps you to easily convert CURL to Python code. You can have a look:

    https://curlconverter.com/

    Also, the CURL that you've attached will be converted to something like this.

    import requests
    
    headers = {
        'accept': 'application/json',
        # requests won't add a boundary if this header is set when you pass files=
        # 'Content-Type': 'multipart/form-data',
    }
    
    files = {
        'strictQuotes': (None, ''),
        'escape': (None, '"'),
        'continueOnError': (None, ''),
        'separator': (None, ';'),
        'deleteFile': (None, ''),
        'simulation': (None, ''),
        'fileName': (None, 'synchronization_file'),
        'headerRow': (None, ''),
        'ignoreLeadingWhitespace': (None, ''),
        'sendNotification': (None, ''),
        'fileId': (None, ''),
        'template': (None, ''),
        'saveResult': (None, ''),
        'batchSize': (None, '1000'),
        'file': open('testSourceFile.csv;type=text/csv', 'rb'),
        'quote': (None, '"'),
    }
    
    response = requests.post('https://genericurl.com/rest/endpoint', headers=headers, files=files)