I am trying to make a FastAPI endpoint where a user can upload documents in json format or in a gzip file format. I can get the endpoint to receive data from these two methods alone/separately, but not together in one endpoint/function. Is there a way to make the same FastAPI endpoint receive either json or a file?
Example with json:
from fastapi import FastAPI
from pydantic import BaseModel
class Document(BaseModel):
words: str
app = FastAPI()
@app.post("/document/")
async def create_item(document_json: Document):
return document_json
Example with file:
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware)
@app.post("/document/")
async def create_item(document_gzip: UploadFile = File(...)):
return document_gzip
Not working example with either-or:
from typing import Optional
from fastapi import FastAPI, File, UploadFile
from fastapi.middleware.gzip import GZipMiddleware
from pydantic import BaseModel
class Document(BaseModel):
words: Optional[str] = None
app = FastAPI()
app.add_middleware(GZipMiddleware)
@app.post("/document/")
async def create_item(
document_json: Document, document_gzip: Optional[UploadFile] = File(None)
):
return document_json, document_gzip