Empty body schema when adding file upload ability to endpoint #9023
-
|
I am developing endpoint on which users will be able to create articles. Code: Any ideas? |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
|
what is |
Beta Was this translation helpful? Give feedback.
-
|
The pydantic schemas you might be using is not correct.. and also there is an issue in the functional parameters i.e., usage of image. |
Beta Was this translation helpful? Give feedback.
-
|
Hi @falkben and @krishnardt, thank you for your answers. Please look at my first post again, I updated it. I want uploading image to be optional. |
Beta Was this translation helpful? Give feedback.
-
|
I believe this is why(https://fastapi.tiangolo.com/tutorial/request-files/): You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json. This is not a limitation of FastAPI, it's part of the HTTP protocol. |
Beta Was this translation helpful? Give feedback.
-
|
Can you try replacing image with the following code....
|
Beta Was this translation helpful? Give feedback.
-
|
I think that it is not possible to use json body and file (image) upload in one handler. Because json is parsed as the whole request body (application/json) and file upload is implemented via multipart/formdata (also whole request body in different format) I can suggest three possible solutions:
|
Beta Was this translation helpful? Give feedback.
-
|
@psowa001, @juntatalor https://github.com/dotX12/pyfa-converter from datetime import datetime
from typing import Optional
from fastapi import FastAPI, UploadFile, File, Form
from pydantic import BaseModel, Field
from pyfa_converter import FormDepends, PyFaDepends
app = FastAPI()
class PostContractBodySchema(BaseModel):
title: str = Field(..., description="Description title")
date: Optional[datetime] = Field(
None, description="Example: 2021-12-14T09:56:31.056Z"
)
@app.post("/form-data-body")
async def example_foo_body_handler(
data: PostContractBodySchema = FormDepends(PostContractBodySchema),
# data1: PostContractBodySchema = PyFaDepends( # OR
# model= PostContractBodySchema, _type=Form
# ),
document: UploadFile = File(...),
):
return {"title": data.title, "date": data.date, "file_name": document.filename} |
Beta Was this translation helpful? Give feedback.
I think that it is not possible to use json body and file (image) upload in one handler. Because json is parsed as the whole request body (application/json) and file upload is implemented via multipart/formdata (also whole request body in different format)
I can suggest three possible solutions: