프레임워크/FastAPI

[FastAPI] FastAPI [19] Request Forms and Files

:) :) 2023. 5. 9. 16:30

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