2
from typing import List, Optional

from fastapi import FastAPI, File, UploadFile
from fastapi.responses import HTMLResponse
from pydantic import BaseModel

app = FastAPI(debug=True)
@app.post("/uploadfiles/")
def create_upload_files(upload_file: UploadFile = File(...)):
     json_data =  ??  upload_file ?? 
     result = model().calculate(json_data)
     return { "estimation": result}


@app.get("/")
async def main():
    content = """
<body>
<form action="/uploadfiles/" enctype="multipart/form-data" method="post">
<input name="upload_file" type="file" multiple>
<input type="submit">
</form>
</body>
    """
    return HTMLResponse(content=content)

I have the above FastAPI app. I need to upload a json file. Thus the upload_file is a json file. Also the model() instance uses a method calculate that takes as input json data. I struggle on how to decode the upload_file from Fast_API to dictionairy format.

I tried upload_file.read() but this returns a bytes array

Could you please help?

A.Papa
  • 486
  • 2
  • 8
  • 20

1 Answers1

6

You can use the standard json module to parse the content by using json.load()--(Doc) from an uploaded JSON file as

from fastapi import FastAPI, File, UploadFile
import json

app = FastAPI(debug=True)


@app.post("/uploadfiles/")
def create_upload_files(upload_file: UploadFile = File(...)):
    json_data = json.load(upload_file.file)
    return {"data_in_file": json_data}

Thus, you will have the JSON contents in your json_data variable.

Alternatively, you can use json.loads()--(Doc) function as

json_data = json.loads(upload_file.file.read())
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    Thanks for the answer ;) I think you need a .read() on json_data = json.load(upload_file.file.read() Can you please edit your answer to close the question it you aggree? – A.Papa Nov 20 '20 at 17:08
  • No. If you are using ***`json.load(...)`***, you must use `upload_file.file` (btw, `json.load(...)` and `json.loads(...)` are different) – JPG Nov 20 '20 at 17:20
  • @A.Papa Updated the answer with few more info. – JPG Nov 20 '20 at 17:24