I\'m trying to POST to an API (Build using SlimPHP) which accepts an image along with additional image meta data in the form of JSON.
I\'ve verified the API works
If you need to post nested JSON data and send files in single request, you need to use json.dumps for these elements (lists and mappings in the example below)
import requests
session = requests.Session()
session.post(login_url, json=your_credentials_dict) # auth , not required
mapping = {"email": "Email", "First Name": "first_name"}
post_data = dict(
mode=1,
lists=json.dumps(["133", "899", "911"]),
mapping=json.dumps(mapping),
)
files_data = {'file': ('your-file-name.csv', file_bytes_content)}
response = session.post(, data=post_data, files=files_data)
And as a result will be sent request like this:
********** post file data with mapping **********
--> REQUEST: POST /v3/contacts/import/file/ HTTP/1.1
--> REQUEST: Host: :4000
--> REQUEST: User-Agent: python-requests/2.23.0
--> REQUEST: Accept-Encoding: gzip, deflate
--> REQUEST: Accept: */*
--> REQUEST: Connection: keep-alive
--> REQUEST: Cookie: jwt=eyJ0e***
--> REQUEST: Content-Length: 654
--> REQUEST: Content-Type: multipart/form-data; boundary=db850c3230988e010b1ebe21be3fb344
--> REQUEST:
--> REQUEST: --db850c3230988e010b1ebe21be3fb344
Content-Disposition: form-data; name="lists"
["7syewz9qUz0CbaqhaGm", "LBfWKJwq4Q"]
--db850c3230988e010b1ebe21be3fb344
Content-Disposition: form-data; name="mode"
2
--db850c3230988e010b1ebe21be3fb344
Content-Disposition: form-data; name="mapping"
{"email": "Email", "First Name": "first_name"}
--db850c3230988e010b1ebe21be3fb344
Content-Disposition: form-data; name="file"; filename="good.csv"
first_name;last_name;email;age
John;Doe;test.testson_1@test.com;50
Mark;Twen;test.testson_2@test.com;20
--db850c3230988e010b1ebe21be3fb344--
requests-toolbelt package was used to generate the log above
https://pypi.org/project/requests-toolbelt/