0

I have a problem uploading a file and creating a new Place object.

Without uploading the file, this code is working.

I send a file and this JSON:

{
  "token": "nhsdnfenfxgejr,gcmncm,nserhdljck,cgntsutkjcl",
  "name": "string",
  "description": "string",
  "lon": 0,
  "lat": 0,
  "url": "string"
}

The response is:

422 
Error: Unprocessable Entity
{
  "detail": [
    {
      "loc": [
        "body",
        "place",
        "token"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "place",
        "name"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "place",
        "description"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "place",
        "lon"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "place",
        "lat"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    },
    {
      "loc": [
        "body",
        "place",
        "url"
      ],
      "msg": "field required",
      "type": "value_error.missing"
    }
  ]
}

Without UploadFile, just create new Place, it works without errors.
This the main def:

main.py

@app.post('/create_place')
def create_place(place: schemas.CreatePlace,file: UploadFile = File(...),  db: Session = 
Depends(get_db)):
if auth.check_auth_user(place.token):
    user_email = auth.decode_token(place.token)
    user = crud.get_user_by_email(db = db,email = user_email['sub'])
    if user.is_admin:

        place_db = crud.get_places_by_name(db, name=place.name)
        if place_db:
            raise HTTPException(status_code=400, detail="Place already added")
        with open('media/'+file.filename, "wb") as image:
            shutil.copyfileobj(file.file, image)
        img = str('media/' + file.filename)
        return crud.create_places(db=db, place=place, img = img)
    else:
         raise HTTPException(status_code=400, detail="You are not admin")

else:
    raise HTTPException(status_code=400, detail="You are not auth")
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • What do you use to send the JSON to FastAPI - the docs interface or you have a frontend (react, angular...)? – elano7 Jun 15 '22 at 21:37
  • i use swagger, from fastapi – ZARAJENIY na 100 Jun 16 '22 at 15:36
  • You wrote you tried without upload and it worked. Did you also try upload only, without create place? – elano7 Jun 17 '22 at 05:46
  • Does this answer your question? [How to add both file and JSON body in a FastAPI POST request?](https://stackoverflow.com/questions/65504438/how-to-add-both-file-and-json-body-in-a-fastapi-post-request) – Gino Mempin Jun 22 '22 at 14:06

0 Answers0