I have API which accepts JSON data and file (png
).
This is my fastapi code:
@app.post("/api/")
async def dummy_file_return(metadata=Body(...),file=File(...)):
print("content_type is")
print(file.content_type)
When accesing with curl
.
$curl -X POST -F file=@0_for_django_testcase.png -F metadata='{"meta":"test"}' localhost:8008/api/
server log shows,
content_type is
image/png
I can see content_type
is guessed automatically and image/png
is set.
Then, I tried the same thing by requests
of python
.
response = requests.post(
url,
data={"metadata":json.dumps({"meta":"test")},
files = {
"file": open('0_for_django_testcase.png','rb')
},
)
console shows
content_type is
content_type
is empty and nothing appears.
Why this difference occurs?
In either way file upload is successed, however there is difference for content_type.
I don't set any header for curl
though, -F
flag secretly send some headers?
Another trial, I tested these patterns with headers, but both returns <Response [400]>
error.
response = requests.post(
url,
data={"metadata":json.dumps({"meta":"test")},
files = {
"file": open('0_for_django_testcase.png','rb')
},
headers={
"Content-Type":"image/png"
}
)
response = requests.post(
url,
data={"metadata":json.dumps({"meta":"test")},
files = {
"file": open('0_for_django_testcase.png','rb')
},
headers={
"Content-Type":"multipart/form-data"
}
)
Any help appreciated.