Home >Backend Development >Python Tutorial >How to Accept Both File and JSON Data in a FastAPI POST Request?

How to Accept Both File and JSON Data in a FastAPI POST Request?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 14:19:10698browse

How to Accept Both File and JSON Data in a FastAPI POST Request?

In FastAPI, to add both file and JSON body in a POST request, one can use the File class to handle File objects and the Body class to handle JSON data. An example of how this can be achieved:

from fastapi import FastAPI, File, UploadFile, Body

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...), data: str = Body(...)):
    # Do something with the file and data
    pass

In this example, the file parameter will handle the uploaded file, while the data parameter will handle the JSON data sent in the request body.

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

Statement:
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