formdataで送る場合
ファイルを送る場合はこっちの方が便利
送り側
const formdata = new FormData();
formdata.append('file', file);
const response = await fetch('/url/to/python',{
method: 'POST',
body: formdata
});
受け側
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post('/url/to/python')
async def import(file: UploadFile = File(...)):
contents = await file.read()
print(file.filename, file.content_type, len(contents))
JSONで送る場合
送り側
const senddata = {
id: '001',
name: testname,
};
const response = await fetch('/url/to/python', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(senddata)
});
受け側
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class senddata(BaseModel):
id: str
name: str
@app.post('/path/to/python')
async def import(data: senddata):
print(data.id, data.name)
PHPの場合のメモ
PHPで受けるとき、formdataで送る場合は$_POST,$_FILESで受けるが、JSONで送る場合は、json_decode(file_get_contents('php://input'),true)で受ける