Developers on my project moved from apllication/json
to multipart/form-data
.
Because of that i wanted to rebuild my api tests but i have a problem with posting json object with multipart/form-data
for example simple sign in request:
json that sends from app for sign in (while application/json
):
{
"session": {
"email": "john_doe@example.com",
"password": "examplepassword"
}
}
With posting through multipart/form-data transforms into
--Boundary+.....
Content-Disposition: form-data; name="session[email]"
john_doe@example.com
--Boundary+.....
Content-Disposition: form-data; name="session[password]"
examplepassword
--Boundary+.....
If I'm understand correctly and as developers approves they still sends same json objects but app automatically forms it like this when its is posted as multipart/form-data. They using AFnetworking
I created next function for multipart posting
def post_request_multipart_with_status_and_response(self, endpoint, data):
request_post = requests.post(self.domain + "%s" % endpoint, files=data, headers=self.header)
status = request_post.status_code
requests_post_json = request_post.json()
return status, requests_post_json
FYI: i only put header with autorization token inside of requests.post
. I don't try to put my boundary or Content type because i know that requests will handle it by itself.
And when i send next data into it - everything works cool:
data = {
"session[email]": (None, "john_doe@example.com"),
"session[password]": (None, "examplepassword")
}
but if i try to send a json into it:
data = {
"session": {
"email": "john_doe@example.com",
"password": "examplepassword"
}
}
data = {(None, json.dumps(data))
}
Then it sends in another manner
Content-Type: multipart/form-data; boundary=AAAbbbCCCd
'
send: b'--AAAbbbCCCd
Content-Disposition: form-data;
{"session": {"password": "examplepassword", "email": "john_doe@example.com"}}
--8a78b52e98d34fecae72d054e577c8ad--
'
So i want requests
to split what it would otherwise send as normal form-data and add it as a separate multipart
field for each node. When i'm passing data = { "session": { "email": "john_doe@example.com", "password": "examplepassword" } }
. Requests will solve this nested structures by itself. Like this session[email]
and this session[password]
automatically