pythonrestfile-uploadpython-requestspython-requests-toolbelt

Python file upload using request multipartencoder with json bdoy


I have the following python function where im trying to upload a file over to an API that accepts a file as multipart stream. The API correctly works with postman, however im struggling to identify the problem here.

I have parameters (json body) to post to the API along with the file which I have tried to encode inside my mp_encoder variable.

def callAPIwithFile(apiData,apiUrl):
    file_ids = ''
    jsonData = {'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report']}
    mp_encoder = MultipartEncoder(fields={'type':apiData['type'],'fromId':apiData['fromid'],'toUserIds':apiData['userIds'],'toGroupIds1':apiData['groupIds'],'toDepartmentIds1':apiData['departmentIds'],'subject':apiData['subject'],'body':apiData['body'],'attachment':apiData['attachment'],'report':apiData['report'],'file': (apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')})
    print mp_encoder
    headers = {'Authorization': 'Bearer jwt'}
    resp = requests.post(apiUrl,headers=headers,data=mp_encoder)
    print resp.text
    print "status code " + str(resp.status_code)

    if resp.status_code == 201:
        print ("Success")
        data = json.loads(resp.text)
        file_ids = data['file_ids']
        print file_ids
    else:
        print ("Failure")

On running the code I get the following errors :

{"statusCode":400,"message":["type must be a valid alpha, beta, Or gamma","body should not be empty"],"error":"Bad Request"}
status code 400
Failure

As per my understanding the JSON Body that im trying to post to the API is not being recognised correctly. How do I go about this?

Please note, I have tried using request.post(apiUrl,file=files,data=data,header=header) which results in an error of unexpected field.


Solution

  • The below answer could solve my problem :

    headers = {'Authorization': 'Bearer '+token}
    mydict = dict(type=apiData['type'], fromId=apiData['fromid'], toUserIds1=apiData['userIds'], toGroupIds=apiData['groupIds'], toDepartmentIds1= apiData['departmentIds'], subject= apiData['subject'], body= apiData['body'], attachment= apiData['attachment'], report= apiData['report'])
    resp=requests.post(apiUrl, headers = headers, files=dict(attachment=(apiData["attachment"], open(apiData["attachment"], 'rb'), 'application/vnd.ms-excel')),data=mydict)