https://fastapi.tiangolo.com/tutorial/request-forms-and-files/
Request Forms and Files - FastAPI
Request Forms and Files You can define files and form fields at the same time using File and Form. Info To receive uploaded files and/or form data, first install python-multipart. E.g. pip install python-multipart. Import File and Form Python 3.9+Python 3.
fastapi.tiangolo.com
<FastAPI 공식문서 참조>
0. Request Forms and Files
Form과 File을 동시에 사용해 복합 field를 정의할 수 있다.
1. Import File and Form
from typing import Annotated
from fastapi import FastAPI, File, Form, UploadFile
2. Define File and Form parameters
복합 field를 위한 정의라도 역시 Body와 Query를 정의할 때와 비슷하게 사용할 수 있다.
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
몇몇은 bytes로, 몇몇은 UploadFile 형식으로 파일들을 가져오게 선언할 수 있다.
* request Body가 JSON이 아니라 form-data로 인코딩 되기 때문에 JSON형식의 body field를 함께 선언할 수 없다.
이는 HTTP protocol, 통신규약에 의한 것이다.
3. Recap
한 번에 데이터와 파일들을 받아야 할 경우 File과 Form을 함께 사용하자.
4. Reference
https://fastapi.tiangolo.com/ko/tutorial/request-forms-and-files/
폼 및 파일 요청 - FastAPI
폼 및 파일 요청 File 과 Form 을 사용하여 파일과 폼을 함께 정의할 수 있습니다. 정보 파일과 폼 데이터를 함께, 또는 각각 업로드하기 위해 먼저 python-multipart를 설치해야합니다. 예 ) pip install pyth
fastapi.tiangolo.com
'프레임워크 > FastAPI' 카테고리의 다른 글
[FastAPI] FastAPI [21] Path Operation Configuration (0) | 2023.05.16 |
---|---|
[FastAPI] FastAPI [20] Handling Errors (0) | 2023.05.09 |
[FastAPI] FastAPI [18] Request Files (0) | 2023.05.09 |
[FastAPI] FastAPI [17] Form data (0) | 2023.05.09 |
[FastAPI] FastAPI [16] Extra Models (0) | 2023.05.02 |