Python Requests: Post JSON and file in single request

前端 未结 6 528
天涯浪人
天涯浪人 2020-12-01 05:16

I need to do a API call to upload a file along with a JSON string with details about the file.

I am trying to use the python requests lib to do this:



        
6条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 05:52

    I have been using requests==2.22.0

    For me , the below code worked.

    import requests
    
    
    data = {
        'var1': 'this',
        'var2': 'that'
    }
    
    r = requests.post("http://api.example.com/v1/api/some/",
        files={'document': open('doocument.pdf', 'rb')},
        data=data,
        headers={"Authorization": "Token jfhgfgsdadhfghfgvgjhN"}. #since I had to authenticate for the same
    )
    
    print (r.json())
    

提交回复
热议问题