0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

javascript fetchとpython fastapiのメモ

0
Last updated at Posted at 2026-08-23

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)で受ける

0
1
0

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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?