Home > Backend Development > Python Tutorial > How to Handle File Uploads and JSON Data Simultaneously in a FastAPI POST Request?

How to Handle File Uploads and JSON Data Simultaneously in a FastAPI POST Request?

Patricia Arquette
Release: 2024-12-15 17:01:10
Original
221 people have browsed it

How to Handle File Uploads and JSON Data Simultaneously in a FastAPI POST Request?

How to add both file and JSON body in a FastAPI POST request?

Method 1: Using File and Form

from fastapi import FastAPI, UploadFile, File, Form

app = FastAPI()

@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
               csvFile: UploadFile = File(...)):
    pass
Copy after login

Method 2: Using Pydantic models and Dependencies

from fastapi import Form, File, UploadFile, FastAPI, Depends
from typing import List, Optional
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class Base(BaseModel):
    name: str
    point: Optional[float] = None
    is_accepted: Optional[bool] = False

def checker(data: str = Form(...)):
    try:
        return Base.model_validate_json(data)
    except ValidationError as e:
        raise HTTPException(
            detail=jsonable_encoder(e.errors()),
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        )

@app.post("/submit")
def submit(base: Base = Depends(checker), files: List[UploadFile] = File(...)):
    return {"JSON Payload": base, "Filenames": [file.filename for file in files]}
Copy after login

Method 3: Using Form data as a single JSON string

from fastapi import FastAPI, status, Form, UploadFile, File, Depends, Request
from pydantic import BaseModel, ValidationError
from fastapi.exceptions import HTTPException
from fastapi.encoders import jsonable_encoder
from typing import Optional, List
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse

app = FastAPI()
templates = Jinja2Templates(directory="templates")

class Base(BaseModel):
    name: str
    point: Optional[float] = None
    is_accepted: Optional[bool] = False

def checker(data: str = Form(...)):
    try:
        return Base.model_validate_json(data)
    except ValidationError as e:
        raise HTTPException(
            detail=jsonable_encoder(e.errors()),
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        )

@app.post("/submit")
def submit(base: Base = Depends(checker), files: List[UploadFile] = File(...)):
    return {"JSON Payload": base, "Filenames": [file.filename for file in files]}
Copy after login

The above is the detailed content of How to Handle File Uploads and JSON Data Simultaneously in a FastAPI POST Request?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template