LoginSignup
5
2

More than 1 year has passed since last update.

[FastAPI]複数ファイルをrequests.post()で渡す

Last updated at Posted at 2022-03-15

外部のスクリプトファイルからFastAPIにrequests.post()で複数ファイルを渡す際につまづいたのでメモをここに残します。

uploadFile.py
from typing import List

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.post("/uploadfiles/")
async def create_upload_files(params:dict,fileList: List[UploadFile]):
    return hogehoge(params, files)

requests.post()で複数ファイルを渡したい場合は下記のようにすることで出来ました。
※dictのキーがエンドポイントのfileList(今回はこの名前にしました)という名前と一致していないとFastAPI側で受け取ることが出来ないので注意が必要です。
{エンドポイントの変数名:タプル(ファイル名、バイナリファイル)}

request.py
import requests
 
url = 'http//hogehogehogehoge:8000//uploadfiles/'
params = {
'キー1':'値1',
'キー2':'値2'
}

fileName1 = 'hoge1.xlsx'
fileName2 = 'hoge2.xlsx'

fileDataBinary1 = open(fileName1, 'rb').read()
fileDataBinary2 = open(fileName2,'rb').read()
#ここはリスト[]でも辞書{}でもどちらでも良いようです。
#FastAPIで受け取った際にfileListにちゃんと格納してくれました
fileList = {
'fileList': (fileName1, fileDataBinary1),
'fileList': (fileName2, fileDataBinary2)
}

#このパターンで書くとファイル渡せますが、ファイル名がfileListとなってしまい、拡張子も消えてしまいます
#fileList = {
#'fileList':fileDataBinary1
#}


res = requests.post(url, data= params, files= fileList)

uploadFile.py
@app.post("/uploadfiles/")
async def create_upload_files(params:dict,fileList: List[UploadFile]):
    # print()でファイル名がしっかり渡せてることが確認できます
    print(file.filename for file in files)
5
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2